Administrator
2023-10-30 fb47d36048e94b9a506d5c153e3dd19a01e37df1
third_data/code_plate_key_manager.py
@@ -6,58 +6,134 @@
import json
import constant
from db.redis_manager import RedisUtils
from third_data import kpl_block_util
from db.redis_manager_delegate import RedisUtils
from third_data import kpl_block_util, kpl_api
from utils import global_util, tool
from log_module import log
from db import redis_manager
from log_module import log, async_log_util
from db import redis_manager_delegate as redis_manager
from log_module.log import logger_kpl_limit_up, logger_kpl_block_can_buy, logger_kpl_debug
from log_module.log import logger_kpl_limit_up, logger_kpl_block_can_buy
from third_data.kpl_util import KPLPlatManager
from trade import trade_manager
from trade import trade_manager, l2_trade_util
# 代码精选板块管理
class KPLCodeJXBlockManager:
    __db = 3
    __redisManager = redis_manager.RedisManager(3)
    __code_blocks = {}
    # 备用
    __code_by_blocks = {}
    __instance = None
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(KPLCodeJXBlockManager, cls).__new__(cls, *args, **kwargs)
        return cls.__instance
    def __get_redis(self):
        return self.__redisManager.getRedis()
    def save_jx_blocks(self, code, blocks):
    def save_jx_blocks(self, code, blocks, by=False):
        if blocks is None:
            return
        if len(blocks) > 2:
            blocks = blocks[:2]
        # 保存前2条数据
        RedisUtils.setex(self.__get_redis(),f"kpl_jx_blocks-{code}", tool.get_expire(), json.dumps(blocks))
        self.__code_blocks[code] = blocks
        if by:
            RedisUtils.setex_async(self.__db, f"kpl_jx_blocks_by-{code}", tool.get_expire(), json.dumps(blocks))
            self.__code_by_blocks[code] = blocks
        else:
            RedisUtils.setex_async(self.__db, f"kpl_jx_blocks-{code}", tool.get_expire(), json.dumps(blocks))
            self.__code_blocks[code] = blocks
    # 获取精选板块
    def get_jx_blocks(self, code):
        if code in self.__code_blocks:
            return self.__code_blocks[code]
        val = RedisUtils.get(self.__get_redis(), f"kpl_jx_blocks-{code}")
        if val is None:
            return None
    def get_jx_blocks(self, code, by=False):
        if by:
            if code in self.__code_by_blocks:
                return self.__code_by_blocks[code]
            val = RedisUtils.get(self.__get_redis(), f"kpl_jx_blocks_by-{code}")
            if val is None:
                return None
            else:
                val = json.loads(val)
                self.__code_by_blocks[code] = val
            return self.__code_by_blocks[code]
        else:
            val = json.loads(val)
            self.__code_blocks[code] = val
        return self.__code_blocks[code]
            if code in self.__code_blocks:
                return self.__code_blocks[code]
            val = RedisUtils.get(self.__get_redis(), f"kpl_jx_blocks-{code}")
            if val is None:
                return None
            else:
                val = json.loads(val)
                self.__code_blocks[code] = val
            return self.__code_blocks[code]
    def get_jx_blocks_cache(self, code, by=False):
        if by:
            return self.__code_by_blocks.get(code)
        else:
            return self.__code_blocks.get(code)
    # 从网络上加载精选板块
    def load_jx_blocks(self, code, buy_1_price, limit_up_price):
        if limit_up_price and buy_1_price:
            # 处理买1,卖1信息
            pre_close_price = round(float(limit_up_price) / 1.1, 2)
            # 如果涨幅大于7%就读取板块
            price_rate = (buy_1_price - pre_close_price) / pre_close_price
            if price_rate > 0.07:
                if not self.get_jx_blocks_cache(code):
                    blocks = kpl_api.getCodeJingXuanBlocks(code)
                    self.save_jx_blocks(code, blocks)
                    async_log_util.info(logger_kpl_block_can_buy,f"{code}:获取到精选板块-{blocks}")
            elif price_rate > 0.03:
                # 添加备用板块
                if not self.get_jx_blocks_cache(code, by=True):
                    blocks = kpl_api.getCodeJingXuanBlocks(code)
                    self.save_jx_blocks(code, blocks, by=True)
                    async_log_util.info(logger_kpl_block_can_buy, f"{code}:获取到精选板块(备用)-{blocks}")
# 开盘啦禁止交易板块管理
class KPLPlateForbiddenManager:
    __redisManager = redis_manager.RedisManager(3)
    __kpl_forbidden_plates_cache = set()
    def __get_redis(self):
        return self.__redisManager.getRedis()
    __instance = None
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(KPLPlateForbiddenManager, cls).__new__(cls, *args, **kwargs)
            cls.__load_datas()
        return cls.__instance
    @classmethod
    def __load_datas(cls):
        __redis = cls.__get_redis()
        try:
            __kpl_forbidden_plates_cache = RedisUtils.smembers(__redis, "kpl_forbidden_plates")
        finally:
            RedisUtils.realse(__redis)
    @classmethod
    def __get_redis(cls):
        return cls.__redisManager.getRedis()
    def save_plate(self, plate):
        self.__kpl_forbidden_plates_cache.add(plate)
        RedisUtils.sadd(self.__get_redis(), "kpl_forbidden_plates", plate)
        RedisUtils.expire(self.__get_redis(), "kpl_forbidden_plates", tool.get_expire())
    def list_all(self):
        return RedisUtils.smembers(self.__get_redis(), "kpl_forbidden_plates")
    def list_all_cache(self):
        return self.__kpl_forbidden_plates_cache
class LimitUpCodesPlateKeyManager:
@@ -217,7 +293,7 @@
            # 后排才能挂单
            return 0, "身位不为后排"
        forbidden_plates = cls.__KPLPlateForbiddenManager.list_all()
        forbidden_plates = cls.__KPLPlateForbiddenManager.list_all_cache()
        if key in forbidden_plates:
            return 0, "不买该板块"
@@ -235,11 +311,9 @@
    @classmethod
    def is_in_top(cls, keys):
        reasons = cls.get_can_buy_key_set()
        log.logger_kpl_debug.debug("市场流入前5:{}", reasons)
        forbidden_plates = cls.__KPLPlateForbiddenManager.list_all()
        forbidden_plates = cls.__KPLPlateForbiddenManager.list_all_cache()
        reasons = reasons - forbidden_plates
        temp_set = keys & reasons
        log.logger_kpl_debug.debug("市场流入前5匹配结果:{}", temp_set)
        if temp_set:
            return True, temp_set
        else:
@@ -259,8 +333,8 @@
    def set_history_limit_up_reason(self, code, reasons):
        self.__history_limit_up_reason_dict[code] = set(reasons)
        RedisUtils.setex(self.__get_redis(),f"kpl_his_limit_up_reason-{code}", tool.get_expire(), json.dumps(list(reasons)))
        logger_kpl_debug.debug(f"设置历史涨停原因:{code}-{reasons}")
        RedisUtils.setex(self.__get_redis(), f"kpl_his_limit_up_reason-{code}", tool.get_expire(),
                         json.dumps(list(reasons)))
    # 如果返回值不为None表示已经加载过历史原因了
    def get_history_limit_up_reason(self, code):
@@ -278,9 +352,13 @@
        else:
            return reasons
    def get_history_limit_up_reason_cache(self, code):
        reasons = self.__history_limit_up_reason_dict.get(code)
        return reasons
    def set_blocks(self, code, blocks):
        self.__blocks_dict[code] = set(blocks)
        RedisUtils.setex(self.__get_redis(),f"kpl_blocks-{code}", tool.get_expire(), json.dumps(list(blocks)))
        RedisUtils.setex(self.__get_redis(), f"kpl_blocks-{code}", tool.get_expire(), json.dumps(list(blocks)))
    def get_blocks(self, code):
        reasons = self.__blocks_dict.get(code)
@@ -311,19 +389,20 @@
class TargetCodePlateKeyManager:
    __redisManager = redis_manager.RedisManager(1)
    __CodesPlateKeysManager = CodesHisReasonAndBlocksManager()
    __KPLCodeJXBlockManager = KPLCodeJXBlockManager()
    def __get_redis(self):
        return self.__redisManager.getRedis()
    # 返回key集合(排除无效板块),今日涨停原因,今日历史涨停原因,历史涨停原因,二级,板块
    # 返回key集合(排除无效板块),今日涨停原因,今日历史涨停原因,历史涨停原因,二级,精选板块
    def get_plate_keys(self, code):
        keys = set()
        k1 = set()
        if code in LimitUpCodesPlateKeyManager.today_total_limit_up_reason_dict:
            k1 = {LimitUpCodesPlateKeyManager.today_total_limit_up_reason_dict[code]}
        # 加载今日历史原因
        k11 = RedisUtils.smembers(self.__get_redis(), f"kpl_limit_up_reason_his-{code}")
        k2 = self.__CodesPlateKeysManager.get_history_limit_up_reason(code)
        # 加载今日历史原因,暂时不需要历史原因了
        k11 = set()  # RedisUtils.smembers(self.__get_redis(), f"kpl_limit_up_reason_his-{code}")
        k2 = self.__CodesPlateKeysManager.get_history_limit_up_reason_cache(code)
        if k2 is None:
            k2 = set()
        k3 = set()
@@ -331,9 +410,13 @@
        if industry:
            k3 = {industry}
        k4 = self.__CodesPlateKeysManager.get_blocks(code)
        if k4 is None:
            k4 = set()
        k4 = set()
        jingxuan_blocks = self.__KPLCodeJXBlockManager.get_jx_blocks_cache(code)
        if not jingxuan_blocks:
            jingxuan_blocks = self.__KPLCodeJXBlockManager.get_jx_blocks_cache(code, by=True)
        if jingxuan_blocks:
            jingxuan_blocks = jingxuan_blocks[:2]
            k4 |= set([x[1] for x in jingxuan_blocks])
        for k in [k1, k11, k2, k3, k4]:
            keys |= k
@@ -358,7 +441,64 @@
    __TargetCodePlateKeyManager = TargetCodePlateKeyManager()
    __LimitUpCodesPlateKeyManager = LimitUpCodesPlateKeyManager()
    __CodesHisReasonAndBlocksManager = CodesHisReasonAndBlocksManager()
    __KPLCodeJXBlockManager = KPLCodeJXBlockManager()
    __CodesTradeStateManager = trade_manager.CodesTradeStateManager()
    __can_buy_compute_result_dict = {}
    @classmethod
    def __remove_from_l2(cls, code, msg):
        # 根据身位移除代码
        # return
        # 下过单的代码不移除
        if trade_manager.CodesTradeStateManager().get_trade_state_cache(code) != trade_manager.TRADE_STATE_NOT_TRADE:
            # 只要下过单的就不移除
            return
        l2_trade_util.forbidden_trade(code, msg=msg)
        logger_kpl_block_can_buy.info(msg)
    @classmethod
    def __is_block_can_buy(cls, code, block, current_limit_up_datas, code_limit_up_reason_dict,
                           yesterday_current_limit_up_codes, limit_up_record_datas):
        # log.logger_kpl_debug.info(f"判断板块是否可买:{block}")
        # is_top_8_record, top_8_record = kpl_block_util.is_record_top_block(code, block, limit_up_record_datas,
        #                                                                    yesterday_current_limit_up_codes, 50)
        # is_top_4_current, top_4_current = kpl_block_util.is_current_top_block(code, block, current_limit_up_datas,
        #                                                                       yesterday_current_limit_up_codes, 50)
        # is_top_4 = is_top_8_record and is_top_4_current
        # msg_list.append(f"\n实时top10(涨停数量:{len(current_limit_up_datas)})")
        # msg_list.append(f"历史top20(涨停数量:{len(top_8_record)})")
        # 获取主板实时身位,剔除高位板
        current_shsz_rank, front_current_shsz_rank_codes = kpl_block_util.get_code_current_rank(code, block,
                                                                                                current_limit_up_datas,
                                                                                                code_limit_up_reason_dict,
                                                                                                yesterday_current_limit_up_codes,
                                                                                                shsz=True)
        record_shsz_rank, record_shsz_rank_codes = kpl_block_util.get_code_record_rank(code, block,
                                                                                       limit_up_record_datas,
                                                                                       code_limit_up_reason_dict,
                                                                                       yesterday_current_limit_up_codes,
                                                                                       shsz=True)
        # 获取主板历史身位
        open_limit_up_codes = kpl_block_util.get_shsz_open_limit_up_codes(code, block, limit_up_record_datas,
                                                                          code_limit_up_reason_dict)
        if open_limit_up_codes:
            # 主板开1
            if current_shsz_rank < len(open_limit_up_codes) + 1 and record_shsz_rank < len(open_limit_up_codes) + 2:
                # 属于龙1,龙2
                return True, f"{tool.get_now_time_str()} {block}:top10涨停板块,主板开1({open_limit_up_codes}),属于主板前龙{len(open_limit_up_codes) + 1}(实时身位-{current_shsz_rank}/{len(current_limit_up_datas)})"
            else:
                if record_shsz_rank >= len(open_limit_up_codes) + 1:
                    cls.__remove_from_l2(code, f"{code}根据身位禁止买入:【{block}】历史身位{record_shsz_rank}")
                return False, f"板块-{block}: top4涨停板块,主板开1({open_limit_up_codes}),不为主板前龙{len(open_limit_up_codes) + 1}(实时身位-{current_shsz_rank}:{front_current_shsz_rank_codes},历史身位-{record_shsz_rank})"
        else:
            if current_shsz_rank == 0 and record_shsz_rank < 2:
                return True, f"{tool.get_now_time_str()} {block}:top4涨停板块,非主板开1,属于龙1,实时涨停列表数量({len(current_limit_up_datas)})"
            else:
                if record_shsz_rank >= 2:
                    cls.__remove_from_l2(code, f"{code}根据身位禁止买入:【{block}】历史身位{record_shsz_rank}")
                return False, f"板块-{block}: top4涨停板块,非主板开1,不为主板龙1(实时身位-{current_shsz_rank}:{front_current_shsz_rank_codes},历史身位-{record_shsz_rank})"
    # 获取可以买的板块
    # current_limit_up_datas: 今日实时涨停
@@ -378,96 +518,44 @@
                    code_limit_up_reason_dict[d[3]] = d[2]
            return code_limit_up_reason_dict
        now_time = int(tool.get_now_time_str().replace(":", ""))
        times = [100000, 103000, 110000, 133000, 150000]
        time_index = 0
        for i in range(len(times)):
            if now_time < times[i]:
                time_index = i
                break
        if current_limit_up_datas is None:
            current_limit_up_datas = []
        # 获取目标代码板块
        keys, k1, k11, k2, k3, k4 = cls.__TargetCodePlateKeyManager.get_plate_keys(code)
        log.logger_kpl_debug.info("{}关键词:今日-{},今日历史-{},历史-{},二级行业-{},代码板块-{}", code, k1, k11, k2, k3, k4)
        # log.logger_kpl_debug.info("{}关键词:今日-{},今日历史-{},历史-{},二级行业-{},代码板块-{}", code, k1, k11, k2, k3, k4)
        keys = set()
        if k1:
            for k in k1:
                if k not in constant.KPL_INVALID_BLOCKS:
                    keys.add(k)
        if not keys:
            for k in k2:
                if k not in constant.KPL_INVALID_BLOCKS:
                    keys.add(k)
        if not keys:
        # 始终获取精选板块
        if True:
            # 获取
            jx_blocks = cls.__KPLCodeJXBlockManager.get_jx_blocks(code)
            if jx_blocks:
                keys |= set([k[1] for k in jx_blocks[:2]])
        log.logger_kpl_debug.info("{}最终关键词:{}", code, keys)
            if k4:
                keys |= k4
                keys = keys - constant.KPL_INVALID_BLOCKS
        # log.logger_kpl_debug.info("{}最终关键词:{}", code, keys)
        # 涨停列表中匹配关键词,返回(板块:代码集合),代码集合中已经排除自身
        if not keys:
            return cls.BLOCK_TYPE_NONE, None, "尚未找到涨停原因"
            return None, "尚未找到涨停原因"
        code_limit_up_reason_dict = {}
        load_code_block()
        msg_list = []
        can_buy_blocks = []
        for block in keys:
            is_top_8_record, top_8_record = kpl_block_util.is_record_top_block(code, block, limit_up_record_datas,
                                                                               yesterday_current_limit_up_codes, 20)
            is_top_4_current, top_4_current = kpl_block_util.is_current_top_block(code, block, current_limit_up_datas,
                                                                                  yesterday_current_limit_up_codes, 10)
            is_top_4 = is_top_8_record and is_top_4_current
            msg_list.append(f"\n实时top10: {top_4_current}(涨停数量:{len(current_limit_up_datas)})")
            msg_list.append(f"历史top20: {top_8_record}")
            # 获取主板实时身位
            current_shsz_rank = kpl_block_util.get_code_current_rank(code, block, current_limit_up_datas,
                                                                     code_limit_up_reason_dict, shsz=True)
            record_shsz_rank = kpl_block_util.get_code_record_rank(code, block, limit_up_record_datas,
                                                                   code_limit_up_reason_dict, shsz=True)
            # 获取主板历史身位
            if is_top_4:
                pen_limit_up_codes = kpl_block_util.get_shsz_open_limit_up_codes(code, block, limit_up_record_datas,
                                                                                 code_limit_up_reason_dict)
                if pen_limit_up_codes:
                    # 主板开1
                    if current_shsz_rank < len(pen_limit_up_codes) + 1 and record_shsz_rank < len(
                            pen_limit_up_codes) + 1:
                        # 属于龙1,龙2
                        can_buy_blocks.append((block,
                                               f"{block}:top4涨停板块,主板开1({pen_limit_up_codes}),属于主板前龙{len(pen_limit_up_codes) + 1}(实时身位-{current_shsz_rank})"))
                        continue
                    else:
                        msg_list.append(
                            f"板块-{block}: top4涨停板块,主板开1({pen_limit_up_codes}),不为主板前龙{len(pen_limit_up_codes) + 1}(实时身位-{current_shsz_rank},历史身位-{record_shsz_rank})")
                        continue
                else:
                    if current_shsz_rank == 0 and record_shsz_rank < 2:
                        can_buy_blocks.append((block, f"{block}:top4涨停板块,非主板开1,属于龙1"))
                        continue
                    else:
                        msg_list.append(
                            f"板块-{block}: top4涨停板块,非主板开1,不为主板龙1(实时身位-{current_shsz_rank},历史身位-{record_shsz_rank})")
                        continue
            can_buy, msg = cls.__is_block_can_buy(code, block, current_limit_up_datas, code_limit_up_reason_dict,
                                                  yesterday_current_limit_up_codes, limit_up_record_datas)
            if can_buy:
                can_buy_blocks.append((block, msg))
            else:
                # 是否满足行业精选流入要求
                is_in_top_input = RealTimeKplMarketData.is_in_top(set([block]))[0]
                if not is_in_top_input:
                    msg_list.append(
                        f"板块-{block}: 非top4涨停板块,不满足精选/行业流入要求")
                    continue
                else:
                    # 是否为主板龙1(实时龙1,历史龙2以内)
                    if current_shsz_rank == 0 and record_shsz_rank < 2:
                        can_buy_blocks.append((block, f"{block}:不是top4涨停板块,满足精选/行业流入要求,满足主板龙1"))
                        continue
                    else:
                        msg_list.append(
                            f"板块-{block}: 不是top4涨停板块,满足精选/行业流入要求,不为主板龙1(实时身位-{current_shsz_rank},历史身位-{record_shsz_rank})")
                        continue
                msg_list.append(msg)
        if len(can_buy_blocks) == len(keys):
            blocks = "/".join([x[0] for x in can_buy_blocks])
            blocks = [x[0] for x in can_buy_blocks]
            blocks_msg = "\n".join([x[1] for x in can_buy_blocks])
            return blocks, blocks_msg
@@ -476,68 +564,26 @@
    # 是否可以下单
    # 返回:是否可以下单,消息,板块类型
    @classmethod
    def can_buy(cls, code, current_limit_up_datas, limit_up_record_datas, yesterday_current_limit_up_codes,
                before_blocks_dict):
    def can_buy(cls, code):
        if constant.TEST:
            return True, "", cls.BLOCK_TYPE_NONE
            return True, cls.BLOCK_TYPE_NONE
        # if True:
        #     # 测试
        #     return True, "不判断板块身位"
        return cls.__can_buy_compute_result_dict.get(code)
        block, block_msg = cls.get_can_buy_block(code, current_limit_up_datas,
                                                 limit_up_record_datas, yesterday_current_limit_up_codes,
                                                 before_blocks_dict)
        if block is None:
    @classmethod
    def __compute_can_buy_blocks(cls, code, current_limit_up_datas, limit_up_record_datas,
                                 yesterday_current_limit_up_codes, before_blocks_dict):
        blocks, block_msg = cls.get_can_buy_block(code, current_limit_up_datas,
                                                  limit_up_record_datas, yesterday_current_limit_up_codes,
                                                  before_blocks_dict)
        if not blocks:
            return False, block_msg
        # ---------------------------------判断目标代码的板块-------------------start------------
        # 判断匹配出的涨停原因,判断是否有已经下单的票
        # reason_need_buy_dict = {}
        # for k in match_limit_up_result:
        #     codes = match_limit_up_result[k]
        #     final_codes_keys = [keys]
        #     for code_ in codes:
        #         temp_key_set = set()
        #         temp_key_set |= cls.__CodesHisReasonAndBlocksManager.get_total_keys(code_)
        #         temp = cls.__LimitUpCodesPlateKeyManager.total_code_keys_dict.get(code_)
        #         if temp:
        #             temp_key_set |= temp
        #         # 二级
        #         industry = global_util.code_industry_map.get(code_)
        #         if industry:
        #             temp_key_set.add(industry)
        #
        #         final_codes_keys.append(temp_key_set)
        #     # 求共同的关键词
        #     intersection = set(final_codes_keys[0])
        #     for s in final_codes_keys:
        #         intersection &= s
        #     log.logger_kpl_debug.info("{}的板块求交集:{}-{}", code, k, intersection)
        #
        #     # 求公共的板块是否在流入前5中
        #     is_in, valid_keys = RealTimeKplMarketData.is_in_top(intersection)
        #     if is_in:
        #         reason_need_buy_dict[k] = (is_in, valid_keys)
        # ---------------------------------判断目标代码的板块-------------------end------------
        # 获取板块可以下单的个数
        # can_buy_codes_count_dict = {}
        #
        # for key__ in match_limit_up_result:
        #     can_buy_count, msg = RealTimeKplMarketData.get_can_buy_codes_count(code, key__)
        #     can_buy_codes_count_dict[key__] = can_buy_count
        # has_available_key = False
        # for key in can_buy_codes_count_dict:
        #     if can_buy_codes_count_dict[key] > 0:
        #         has_available_key = True
        #         break
        # if not has_available_key:
        #     return False, f"匹配到的【{','.join(match_limit_up_result.keys())}】没在精选/行业可以买入的板块中"
        # ---------------------------------加载已经下单/成交的代码信息------------start-------------
        # match_reasons = match_limit_up_result.keys()
        # 判断匹配到的原因是否已经有下单/买入成功的代码
        codes_delegate = set(trade_manager.get_codes_by_trade_states(
        codes_delegate = set(cls.__CodesTradeStateManager.get_codes_by_trade_states_cache(
            {trade_manager.TRADE_STATE_BUY_DELEGATED, trade_manager.TRADE_STATE_BUY_PLACE_ORDER}))
        codes_success = set(trade_manager.get_codes_by_trade_states(
        codes_success = set(cls.__CodesTradeStateManager.get_codes_by_trade_states_cache(
            {trade_manager.TRADE_STATE_BUY_SUCCESS}))
        codes = codes_delegate | codes_success
@@ -549,7 +595,7 @@
        for c in codes:
            keys_, k1_, k11_, k2_, k3_, k4_ = cls.__TargetCodePlateKeyManager.get_plate_keys(c)
            # 实时涨停原因
            trade_codes_blocks_dict[c] = k1_
            trade_codes_blocks_dict[c] = k1_ | k4_
        # 统计板块中的代码
        trade_block_codes_dict = {}
        for c in trade_codes_blocks_dict:
@@ -563,35 +609,67 @@
                trade_block_codes_dict[b].add(c)
        # ---------------------------------加载已经下单/成交的代码信息------------end-------------
        msg_list = []
        for key in [block]:
        for key in blocks:
            # 板块中已经有成交的就不下单了
            if key in trade_success_blocks_count:
                success_codes_count = len(trade_success_blocks_count[key])
                if success_codes_count >= 2:
                    msg_list.append(f"【{key}】中已经有{success_codes_count}个成交代码")
                    log.logger_kpl_debug.debug(f"{code}:板块({key})已经有成交【{trade_success_blocks_count[key]}】")
                    continue
                # 10:30以后买1个
                if int(tool.get_now_time_str().replace(":", "")) > int("103000") and success_codes_count >= 1:
                if success_codes_count >= 1:
                    msg_list.append(f"【{key}】中已经有{success_codes_count}个成交代码")
                    log.logger_kpl_debug.debug(f"{code}:板块({key})已经有成交【{trade_success_blocks_count[key]}】")
                    continue
            return True, block_msg
            # 板块可以下单数量
            # if trade_block_codes_dict.get(key) is None or len(trade_block_codes_dict.get(key)) < \
            #         can_buy_codes_count_dict[key]:
            #     order_count = len(trade_block_codes_dict.get(key)) if key in trade_block_codes_dict else 0
            #     logger_kpl_block_can_buy.info(
            #         f"code={code}:【{key}】可以下单,现有数量:{order_count} 最大数量:{can_buy_codes_count_dict[key]}")
            #     return True, f"可以下单,板块:【{key}】,板块中已经下单的数量:{order_count}"
            # else:
            #     order_count = len(trade_block_codes_dict.get(key))
            #     msg_list.append(f"【{key}】中下单代码数量{order_count}/允许下单数量{can_buy_codes_count_dict[key]}")
        return False, ",".join(msg_list)
    # 更新代码板块判断是否可以买的结果
    @classmethod
    def update_can_buy_blocks(cls, code, current_limit_up_datas, limit_up_record_datas,
                              yesterday_current_limit_up_codes,
                              before_blocks_dict):
        can_buy, msg = cls.__compute_can_buy_blocks(code, current_limit_up_datas, limit_up_record_datas,
                                                    yesterday_current_limit_up_codes,
                                                    before_blocks_dict)
        # 保存板块计算结果
        cls.__can_buy_compute_result_dict[code] = (can_buy, msg)
    # 判断是否为真老大
    @classmethod
    def __is_real_first_limit_up(cls, code, block, current_limit_up_datas, limit_up_record_datas,
                                 yesterday_current_limit_up_codes,
                                 before_blocks_dict):
        # 加载涨停代码的目标板块
        def load_code_block():
            if limit_up_record_datas:
                for d in limit_up_record_datas:
                    if d[2] in constant.KPL_INVALID_BLOCKS and d[3] in before_blocks_dict:
                        code_limit_up_reason_dict[d[3]] = list(before_blocks_dict.get(d[3]))[0]
                    else:
                        code_limit_up_reason_dict[d[3]] = d[2]
            return code_limit_up_reason_dict
        if current_limit_up_datas is None:
            current_limit_up_datas = []
        if limit_up_record_datas is None:
            limit_up_record_datas = []
        code_limit_up_reason_dict = {}
        load_code_block()
        can_buy, msg = cls.__is_block_can_buy(code, block, current_limit_up_datas, code_limit_up_reason_dict,
                                              yesterday_current_limit_up_codes, limit_up_record_datas)
        return can_buy, msg
    @classmethod
    def is_need_cancel(cls, code, limit_up_reason, current_limit_up_datas, limit_up_record_datas,
                       yesterday_current_limit_up_codes,
                       before_blocks_dict):
        can_buy, msg = cls.__is_real_first_limit_up(code, limit_up_reason, current_limit_up_datas,
                                                    limit_up_record_datas,
                                                    yesterday_current_limit_up_codes,
                                                    before_blocks_dict)
        if not can_buy:
            logger_kpl_block_can_buy.warning(f"{code} 根据涨停原因({limit_up_reason})匹配不能买")
        return not can_buy
if __name__ == "__main__":
    pass