From b51b2ae184fad5aaf37a78903987e064f192d430 Mon Sep 17 00:00:00 2001
From: Administrator <admin@example.com>
Date: 星期一, 26 五月 2025 11:35:20 +0800
Subject: [PATCH] 大单解析修改

---
 third_data/code_plate_key_manager.py | 1282 +++++++++++++++++++++++++++++++++++++++++++++------------
 1 files changed, 998 insertions(+), 284 deletions(-)

diff --git a/third_data/code_plate_key_manager.py b/third_data/code_plate_key_manager.py
index 0a08ae8..ebacd5c 100644
--- a/third_data/code_plate_key_manager.py
+++ b/third_data/code_plate_key_manager.py
@@ -3,66 +3,110 @@
 """
 
 # 娑ㄥ仠浠g爜鍏抽敭璇嶆澘鍧楃鐞�
+import copy
+import datetime
+import itertools
 import json
+import time
 
 import constant
+from code_attribute import gpcode_manager
 from db.redis_manager_delegate import RedisUtils
-from third_data import kpl_block_util
-from utils import global_util, tool
-from log_module import log
-from db import redis_manager_delegate as redis_manager
+from third_data import kpl_block_util, kpl_api, kpl_util
+from settings.trade_setting import MarketSituationManager
+from third_data.history_k_data_manager import HistoryKDataManager
+from third_data.history_k_data_util import HistoryKDatasUtils
+from third_data.kpl_data_constant import LimitUpCodesBlockRecordManager, ContainsLimitupCodesBlocksManager
+from third_data.third_blocks_manager import BlockMapManager
+from utils import global_util, tool, buy_condition_util
+from log_module import async_log_util
+from db import redis_manager_delegate as redis_manager, mysql_data_delegate as mysql_data
 
-from log_module.log import logger_kpl_limit_up, logger_kpl_block_can_buy, logger_kpl_debug
+from log_module.log import logger_kpl_block_can_buy, logger_kpl_jx_out, logger_kpl_jx_in, logger_debug, \
+    logger_kpl_latest_gaobiao
 from third_data.kpl_util import KPLPlatManager
-from trade import trade_manager, l2_trade_util
-
+from trade import l2_trade_util, trade_constant
 
 # 浠g爜绮鹃�夋澘鍧楃鐞�
+from utils.kpl_data_db_util import KPLLimitUpDataUtil
+
+
 class KPLCodeJXBlockManager:
+    __db = 3
     __redisManager = redis_manager.RedisManager(3)
     __code_blocks = {}
     # 澶囩敤
     __code_by_blocks = {}
+    # 婵�杩涗拱鐨勪唬鐮佹澘鍧�
+    __code_blocks_for_radical_buy = {}
 
-    def __get_redis(self):
-        return self.__redisManager.getRedis()
+    __instance = None
 
-    def save_jx_blocks(self, code, blocks, by=False):
-        if blocks is None:
+    def __new__(cls, *args, **kwargs):
+        if not cls.__instance:
+            cls.__instance = super(KPLCodeJXBlockManager, cls).__new__(cls, *args, **kwargs)
+            try:
+                cls.__load_data()
+            except Exception as e:
+                logger_debug.exception(e)
+        return cls.__instance
+
+    @classmethod
+    def __load_data(cls):
+        keys = RedisUtils.keys(cls.__get_redis(), "kpl_jx_blocks_by-*")
+        if keys:
+            for k in keys:
+                val = RedisUtils.get(cls.__get_redis(), k)
+                val = json.loads(val)
+                cls.__code_by_blocks[k.split("-")[1]] = (val, time.time())
+        keys = RedisUtils.keys(cls.__get_redis(), "kpl_jx_blocks-*")
+        if keys:
+            for k in keys:
+                val = RedisUtils.get(cls.__get_redis(), k)
+                val = json.loads(val)
+                cls.__code_blocks[k.split("-")[1]] = (val, time.time())
+        keys = RedisUtils.keys(cls.__get_redis(), "kpl_jx_blocks_radical-*")
+        if keys:
+            for k in keys:
+                val = RedisUtils.get(cls.__get_redis(), k)
+                val = json.loads(val)
+                cls.__code_blocks_for_radical_buy[k.split("-")[1]] = (val, time.time())
+
+    @classmethod
+    def __get_redis(cls):
+        return cls.__redisManager.getRedis()
+
+    def save_jx_blocks(self, code, blocks: list, current_limit_up_blocks: set, by=False):
+        if not blocks:
             return
+        final_blocks = copy.deepcopy(blocks)
         if len(blocks) > 2:
-            blocks = blocks[:2]
-
+            final_blocks.clear()
+            for b in blocks:
+                if b not in constant.KPL_INVALID_BLOCKS:
+                    final_blocks.append(b)
+            if len(final_blocks) < 2:
+                final_blocks = blocks
         # 淇濆瓨鍓�2鏉℃暟鎹�
         if by:
-            RedisUtils.setex(self.__get_redis(), f"kpl_jx_blocks_by-{code}", tool.get_expire(), json.dumps(blocks))
-            self.__code_by_blocks[code] = blocks
+            RedisUtils.setex_async(self.__db, f"kpl_jx_blocks_by-{code}", tool.get_expire(), json.dumps(final_blocks))
+            self.__code_by_blocks[code] = (final_blocks, time.time())
         else:
-            RedisUtils.setex(self.__get_redis(), f"kpl_jx_blocks-{code}", tool.get_expire(), json.dumps(blocks))
-            self.__code_blocks[code] = blocks
+            RedisUtils.setex_async(self.__db, f"kpl_jx_blocks-{code}", tool.get_expire(), json.dumps(final_blocks))
+            self.__code_blocks[code] = (final_blocks, time.time())
 
-    # 鑾峰彇绮鹃�夋澘鍧�
-    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:
-            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 save_jx_blocks_for_radical_buy(self, code, blocks: list):
+        if not blocks:
+            return
+        RedisUtils.setex_async(self.__db, f"kpl_jx_blocks_radical-{code}", tool.get_expire(), json.dumps(blocks))
+        self.__code_blocks_for_radical_buy[code] = (blocks, time.time())
+
+    # 鑾峰彇绮鹃�夋澘鍧楋紙婵�杩涗拱锛�
+    def get_jx_blocks_radical(self, code):
+        blocks_info = self.__code_blocks_for_radical_buy.get(code)
+        if blocks_info:
+            return set(blocks_info[0])
+        return None
 
     def get_jx_blocks_cache(self, code, by=False):
         if by:
@@ -70,11 +114,131 @@
         else:
             return self.__code_blocks.get(code)
 
+    # 浠庣綉缁滀笂鍔犺浇绮鹃�夋澘鍧�, 褰撳墠娑ㄥ仠鐨勬澘鍧�
+    def load_jx_blocks(self, code, buy_1_price, limit_up_price, current_limit_up_blocks):
+        try:
+            # logger_kpl_block_can_buy.info(f"鍑嗗鏇存柊绮鹃�夋澘鍧楋細{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) / tool.get_limit_up_rate(code), 2)
+                # 濡傛灉娑ㄥ箙澶т簬7%灏辫鍙栨澘鍧�
+                price_rate = (buy_1_price - pre_close_price) / pre_close_price
+                if price_rate > 0.07:
+                    jx_blocks_info = self.get_jx_blocks_cache(code)
+                    if not jx_blocks_info:
+                        start_time = time.time()
+                        blocks = kpl_api.getCodeBlocks(code)
+                        async_log_util.info(logger_kpl_block_can_buy,
+                                            f"{code}:鑾峰彇鍒扮簿閫夋澘鍧�-{blocks}  鑰楁椂:{int(time.time() - start_time)}s")
+                        self.save_jx_blocks(code, blocks, current_limit_up_blocks)
+                        # 璺熼殢绮鹃�夋澘鍧椾竴璧锋洿鏂�
+                        self.load_jx_blocks_radical(code)
+                    else:
+                        # 杩樻病娑ㄥ仠鐨勯渶瑕佹洿鏂扮簿閫夋澘鍧� 鏇存柊绮鹃�夋澘鍧�
+                        if abs(float(buy_1_price) - float(limit_up_price)) >= 0.001:
+                            # 闈炴定鍋滅姸鎬�
+                            UPDATE_TIME_SPACE = 5 * 60
+                            time_diff = tool.trade_time_sub(tool.get_now_time_str(), "09:30:00")
+                            if time_diff < 0:
+                                UPDATE_TIME_SPACE = 60 * 60
+                            else:
+                                UPDATE_TIME_SPACE = int(time_diff / 30) + 60
+                                if UPDATE_TIME_SPACE > 5 * 60:
+                                    UPDATE_TIME_SPACE = 5 * 60
+
+                            if time.time() - jx_blocks_info[1] > UPDATE_TIME_SPACE:
+                                start_time = time.time()
+                                # 璺濈涓婃鏇存柊鏃堕棿杩囧幓浜�5鍒嗛挓
+                                blocks = kpl_api.getCodeBlocks(code)
+                                async_log_util.info(logger_kpl_block_can_buy,
+                                                    f"{code}:鑾峰彇鍒扮簿閫夋澘鍧楋紙鏇存柊锛�-{blocks}  鑰楁椂:{int(time.time() - start_time)}s")
+                                self.save_jx_blocks(code, blocks, current_limit_up_blocks)
+                                # 璺熼殢绮鹃�夋澘鍧椾竴璧锋洿鏂�
+                                self.load_jx_blocks_radical(code)
+                elif price_rate > 0.03:
+                    # 娣诲姞澶囩敤鏉垮潡
+                    if not self.get_jx_blocks_cache(code, by=True):
+                        start_time = time.time()
+                        blocks = kpl_api.getCodeBlocks(code)
+                        self.save_jx_blocks(code, blocks, current_limit_up_blocks, by=True)
+                        async_log_util.info(logger_kpl_block_can_buy,
+                                            f"{code}:鑾峰彇鍒扮簿閫夋澘鍧�(澶囩敤)-{blocks}  鑰楁椂:{int(time.time() - start_time)}s")
+                        # 璺熼殢绮鹃�夋澘鍧椾竴璧锋洿鏂�
+                        self.load_jx_blocks_radical(code)
+
+                if price_rate > 0.03:
+                    if not self.__code_blocks_for_radical_buy.get(code):
+                        self.load_jx_blocks_radical(code)
+        except Exception as e:
+            logger_kpl_block_can_buy.error(f"{code} 鑾峰彇鏉垮潡鍑洪敊")
+            logger_kpl_block_can_buy.exception(e)
+
+    def load_jx_blocks_radical(self, code):
+        start_time = time.time()
+        blocks = kpl_api.getCodeJingXuanBlocks(code, jx=False)
+        blocks = set([b[1] for b in blocks])
+        # fblocks = BlockMapManager().filter_blocks(blocks)
+        async_log_util.info(logger_kpl_block_can_buy,
+                            f"{code}:鑾峰彇鍒版澘鍧�(婵�杩涗拱) 杩囨护鍓�-{blocks} 鑰楁椂:{int(time.time() - start_time)}s")
+        self.save_jx_blocks_for_radical_buy(code, list(blocks))
+
+
+# 绂佹涓嬪崟鐨勬澘鍧�
+class ForbiddenBlockManager:
+    __db = 3
+    __redisManager = redis_manager.RedisManager(3)
+    __instance = None
+    __forbidden_blocks = set()
+
+    def __new__(cls, *args, **kwargs):
+        if not cls.__instance:
+            cls.__instance = super(ForbiddenBlockManager, cls).__new__(cls, *args, **kwargs)
+            cls.__load_data()
+        return cls.__instance
+
+    @classmethod
+    def __get_redis(cls):
+        return cls.__redisManager.getRedis()
+
+    # 鍔犺浇鏁版嵁
+    @classmethod
+    def __load_data(cls):
+        blocks = cls.__get_redis().smembers("forbidden_blocks")
+        if blocks:
+            for b in blocks:
+                cls.__forbidden_blocks.add(b)
+
+    def add(self, block):
+        self.__forbidden_blocks.add(block)
+        RedisUtils.sadd_async(self.__db, "forbidden_blocks", block)
+        RedisUtils.expire_async(self.__db, "forbidden_blocks", tool.get_expire())
+
+    def remove(self, block):
+        if block in self.__forbidden_blocks:
+            self.__forbidden_blocks.remove(block)
+        RedisUtils.srem_async(self.__db, "forbidden_blocks", block)
+
+    def get_blocks(self):
+        return copy.deepcopy(self.__forbidden_blocks)
+
+    def is_in(self, block):
+        return block in self.__forbidden_blocks
+
 
 # 寮�鐩樺暒绂佹浜ゆ槗鏉垮潡绠$悊
 class KPLPlateForbiddenManager:
-    __redisManager = redis_manager.RedisManager(3)
+    """
+    涓嶈兘涔扮殑鏉垮潡绠$悊
+    """
+    __redis_manager = redis_manager.RedisManager(3)
     __kpl_forbidden_plates_cache = set()
+    # 宸茬粡鍒犻櫎浜嗙殑鏉垮潡
+    __deleted_kpl_forbidden_plates_cache = set()
+
+    # 鐩戞帶鐨勯珮鏍囨澘鍧椾唬鐮佸瓧鍏革細{"鏉垮潡":{"浠g爜1","浠g爜2"}}
+    __watch_block_high_codes = {}
+    # 楂樻爣浠g爜
+    __watch_high_codes = set()
 
     __instance = None
 
@@ -88,18 +252,32 @@
     def __load_datas(cls):
         __redis = cls.__get_redis()
         try:
-            __kpl_forbidden_plates_cache = RedisUtils.smembers(__redis, "kpl_forbidden_plates")
+            cls.__kpl_forbidden_plates_cache = RedisUtils.smembers(__redis, "kpl_forbidden_plates")
+            cls.__deleted_kpl_forbidden_plates_cache = RedisUtils.smembers(__redis, "deleted_kpl_forbidden_plates")
         finally:
             RedisUtils.realse(__redis)
+        cls.__load_latest_gb()
 
     @classmethod
     def __get_redis(cls):
-        return cls.__redisManager.getRedis()
+        return cls.__redis_manager.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())
+
+        self.__deleted_kpl_forbidden_plates_cache.discard(plate)
+        RedisUtils.srem(self.__get_redis(), "deleted_kpl_forbidden_plates", plate)
+        RedisUtils.expire(self.__get_redis(), "deleted_kpl_forbidden_plates", tool.get_expire())
+
+    def delete_plate(self, plate):
+        self.__kpl_forbidden_plates_cache.discard(plate)
+        RedisUtils.srem(self.__get_redis(), "kpl_forbidden_plates", plate)
+        RedisUtils.expire(self.__get_redis(), "kpl_forbidden_plates", tool.get_expire())
+        self.__deleted_kpl_forbidden_plates_cache.add(plate)
+        RedisUtils.sadd(self.__get_redis(), "deleted_kpl_forbidden_plates", plate)
+        RedisUtils.expire(self.__get_redis(), "deleted_kpl_forbidden_plates", tool.get_expire())
 
     def list_all(self):
         return RedisUtils.smembers(self.__get_redis(), "kpl_forbidden_plates")
@@ -107,11 +285,137 @@
     def list_all_cache(self):
         return self.__kpl_forbidden_plates_cache
 
+    def list_all_deleted_cache(self):
+        return self.__deleted_kpl_forbidden_plates_cache
+
+    def is_in_cache(self, plate):
+        if self.__kpl_forbidden_plates_cache and plate in self.__kpl_forbidden_plates_cache:
+            return True
+        return False
+
+    @classmethod
+    def __load_latest_gb(cls):
+        """
+        鍔犺浇鏈�杩戠殑甯傚満楂樻爣
+        @return:
+        """
+        # 鑾峰彇鏈�杩�10涓氦鏄撴棩娑ㄥ仠鐨勬定鍋滄暟鎹�
+        dates = HistoryKDatasUtils.get_latest_trading_date_cache(10)
+        if not dates:
+            return
+        min_date = dates[-1]
+        sql = f"SELECT r.`_code`, r.`_hot_block_name`, r.`_day`, r.`_open` FROM `kpl_limit_up_record` r WHERE r.`_day`>='{min_date}'"
+        mysqldb = mysql_data.Mysqldb()
+        results = mysqldb.select_all(sql)
+        code_days_map = {}
+        # 姣忕偢鏉�
+        f_code_days_map = {}
+        for r in results:
+            if r[0] not in code_days_map:
+                code_days_map[r[0]] = set()
+            code_days_map[r[0]].add(r[2])
+            if not r[3]:
+                if r[0] not in f_code_days_map:
+                    f_code_days_map[r[0]] = set()
+                f_code_days_map[r[0]].add(r[2])
+
+        # 杩囨护娑ㄥ仠娆℃暟>=3娆$殑鏁版嵁
+        target_codes = set()
+        for code in code_days_map:
+            if f_code_days_map.get(code) and (len(f_code_days_map.get(code)) >= 4 or (
+                    tool.is_ge_code(code) and len(f_code_days_map.get(code)) >= 2)):
+                # 涓旀湁3澶╁睘浜庤繛缁定鍋�
+                day_list = list(code_days_map[code])
+                day_list.sort(reverse=True)
+                step = 3
+                has_continue = False
+                for i in range(0, len(day_list) - step + 1):
+                    item_list = day_list[i:i + step]
+                    # 鏄惁灞炰簬杩炵画娑ㄥ仠
+                    is_sub = False
+                    for j in range(0, len(dates) - step):
+                        if f"{dates[j:j + step]}" == f"{item_list}":
+                            is_sub = True
+                            break
+                    if is_sub:
+                        has_continue = True
+                        break
+                if not has_continue:
+                    continue
+
+                has_big_deal = False
+                # 鏈�杩�10涓氦鏄撴棩鐨勬垚浜ら瑕佸ぇ浜�10浜�
+                volumes_data = HistoryKDataManager().get_history_bars(code, dates[0])
+                if volumes_data:
+                    for d in volumes_data[:10]:
+                        if d["amount"] > 10e8:
+                            has_big_deal = True
+                            break
+                if not has_big_deal:
+                    continue
+                target_codes.add(code)
+        # 浠g爜瀵瑰簲鐨勬澘鍧�
+        code_blocks = {}
+        for r in results:
+            if r[0] not in target_codes:
+                continue
+            if r[0] not in code_blocks:
+                code_blocks[r[0]] = set()
+            code_blocks[r[0]].add(kpl_util.filter_block(r[1]))
+        # 鎵�鏈夋澘鍧楀搴旂殑浠g爜闆嗗悎
+        block_codes = {}
+        for code in code_blocks:
+            for b in code_blocks[code]:
+                if b in constant.KPL_INVALID_BLOCKS:
+                    continue
+                if b not in block_codes:
+                    block_codes[b] = set()
+                block_codes[b].add(code)
+        print(block_codes)
+        cls.__watch_block_high_codes = block_codes
+        logger_kpl_latest_gaobiao.info(f"{block_codes}")
+        cls.__watch_high_codes.clear()
+        for b in block_codes:
+            cls.__watch_high_codes |= block_codes[b]
+
+        for k in block_codes:
+            print(k, [(x, gpcode_manager.get_code_name(x)) for x in block_codes[k]])
+
+    def get_watch_high_codes(self):
+        return self.__watch_high_codes
+
+    def get_watch_high_codes_by_block(self, b):
+        return self.__watch_block_high_codes.get(b)
+
+    def compute(self, code_rate_dict: dict):
+        """
+        鏍规嵁姣斾緥璁$畻闇�瑕佹媺榛戠殑浠g爜
+        @param code_rate_dict: 娑ㄥ箙鐧惧垎鏁�
+        @return:
+        """
+        try:
+            if self.__watch_block_high_codes:
+                forbidden_blocks = set()
+                for b in self.__watch_block_high_codes:
+                    total_rate = 0
+                    for code in self.__watch_block_high_codes[b]:
+                        if code in code_rate_dict:
+                            total_rate += code_rate_dict.get(code)
+                    average_rate = total_rate / len(self.__watch_block_high_codes[b])
+                    if average_rate < 1:
+                        forbidden_blocks.add(b)
+                    # async_log_util.info(logger_debug, f"鏉垮潡骞冲潎娑ㄥ箙 {b}-{average_rate}")
+
+                self.__kpl_forbidden_plates_cache = forbidden_blocks
+                async_log_util.info(logger_debug, f"鎷夐粦鏉垮潡锛歿forbidden_blocks}")
+        except Exception as e:
+            logger_debug.exception(e)
+
 
 class LimitUpCodesPlateKeyManager:
     # 浠婃棩娑ㄥ仠鍘熷洜
     today_limit_up_reason_dict = {}
-    today_total_limit_up_reason_dict = {}
+    __today_total_limit_up_reason_dict = {}
     total_code_keys_dict = {}
     total_key_codes_dict = {}
     __redisManager = redis_manager.RedisManager(1)
@@ -119,7 +423,7 @@
     def __get_redis(self):
         return self.__redisManager.getRedis()
 
-    # 鑾峰彇浠婃棩娑ㄥ仠鏁版嵁锛屾牸寮忥細[(浠g爜,娑ㄥ仠鍘熷洜)]
+    # 鑾峰彇浠婃棩娑ㄥ仠鏁版嵁锛屾牸寮忥細[(浠g爜,娑ㄥ仠鍘熷洜,绮鹃�夋澘鍧楀垪琛�)]
     def set_today_limit_up(self, datas):
         temp_dict = {}
         if datas:
@@ -132,16 +436,17 @@
         self.set_today_total_limit_up(datas)
 
     # 璁剧疆浠婃棩鍘嗗彶娑ㄥ仠鏁版嵁
-    def set_today_total_limit_up(self, datas):
+    # 鏍煎紡锛�(浠g爜,娑ㄥ仠鍘熷洜,绮鹃�夋澘鍧楀垪琛�)
+    @classmethod
+    def set_today_total_limit_up(cls, datas):
         for item in datas:
             code = item[0]
-            self.today_total_limit_up_reason_dict[code] = item[1]
+            # 璁剧疆娑ㄥ仠浠g爜鐨勬澘鍧楀強鍘熷洜
+            cls.__today_total_limit_up_reason_dict[code] = (item[1], item[2])
 
-    # 浠婃棩娑ㄥ仠鍘熷洜鍙樺寲
-    def set_today_limit_up_reason_change(self, code, from_reason, to_reason):
-        RedisUtils.sadd(self.__get_redis(), f"kpl_limit_up_reason_his-{code}", from_reason)
-        RedisUtils.expire(self.__get_redis(), f"kpl_limit_up_reason_his-{code}", tool.get_expire())
-        self.__set_total_keys(code)
+    @classmethod
+    def get_today_limit_up_reason(cls, code):
+        return cls.__today_total_limit_up_reason_dict.get(code)
 
     # 璁剧疆浠g爜鐨勪粖鏃ユ定鍋滃師鍥�
     def __set_total_keys(self, code):
@@ -157,7 +462,7 @@
                 self.total_key_codes_dict[k] = set()
             self.total_key_codes_dict[k].add(code)
 
-        logger_kpl_limit_up.info("{}鏉垮潡鍏抽敭璇�:{}", code, keys)
+        # logger_kpl_limit_up.info("{}鏉垮潡鍏抽敭璇�:{}", code, keys)
 
     # 鏍规嵁浼犲叆鐨勫叧閿瘝涓庢定鍋滀唬鐮佷俊鎭尮閰嶈韩浣�
 
@@ -183,8 +488,10 @@
 
 # 瀹炴椂寮�鐩樺暒甯傚満鏁版嵁
 class RealTimeKplMarketData:
-    # 绮鹃�夊墠5
-    top_5_reason_list = []
+    # 娴佸叆缂撳瓨 [ID, 鏉垮潡鍚嶇О, 鏉垮潡娑ㄥ箙, 娴佸叆閲戦]
+    top_in_list_cache = []
+    # 娴佸嚭缂撳瓨
+    top_out_list_cache = []
     # 琛屼笟鍓�5
     top_5_industry_list = []
     #
@@ -194,31 +501,156 @@
     __KPLPlateForbiddenManager = KPLPlateForbiddenManager()
     __LimitUpCodesPlateKeyManager = LimitUpCodesPlateKeyManager()
     __KPLPlatManager = KPLPlatManager()
+    # 绮鹃�夋祦鍏ュ墠鍑�
+    __top_jx_blocks = []
+    # 绮鹃�夋祦鍑哄墠鍑�
+    __top_jx_out_blocks = []
+    # 绮鹃�夋澘鍧楁祦鍏ラ噾棰�
+    __jx_blocks_in_money_dict = {}
+    # 甯傚満琛屾儏鐑害锛岄粯璁や负60
+    __market_strong = 60
 
     @classmethod
-    def set_top_5_reasons(cls, datas):
-        temp_list = []
-        for d in datas:
-            cls.total_reason_dict[d[1]] = d
-        # 鎺掑簭
-        for i in range(0, len(datas)):
-            if datas[i][1] not in constant.KPL_INVALID_BLOCKS:
-                # 锛堝悕绉�,鍑�娴佸叆閲戦,鎺掑悕锛�
-                temp_list.append((datas[i][1], datas[i][3], len(temp_list)))
-                # 鍙幏鍙栧墠10涓�
-                if len(temp_list) > 10:
-                    break
-                if datas[i][3] < 3 * 10000 * 10000:
-                    break
+    def get_jingxuan_in_block_threshold_count(cls):
+        """
+        鑾峰彇涔扮簿閫夋祦鍏ュ墠鍑�
+        @return:
+        """
+        score = 60
+        if cls.__market_strong is not None:
+            score = int(cls.__market_strong)
+        for info in constant.RADICAL_BUY_TOP_IN_COUNT_BY_MARKET_STRONG:
+            if info[0] <= score < info[1]:
+                return info[2]
+        return 10
 
-        for temp in temp_list:
-            names = cls.__KPLPlatManager.get_same_plat_names_by_id(temp[0])
-            for name in names:
-                if name == temp[1]:
-                    continue
-                temp_list.append((name, temp[1], temp[2]))
-        cls.top_5_reason_list = temp_list
-        cls.__reset_top_5_dict()
+    @classmethod
+    def set_market_jingxuan_blocks(cls, datas):
+        """
+        璁剧疆绮鹃�夋祦鍏ユ暟鎹�
+        @param datas:[(鏉垮潡缂栧彿,鏉垮潡鍚嶇О,娑ㄥ箙, 鏉垮潡娴佸叆閲戦)]
+        @return:
+        """
+        # 娴佸叆闃堝��
+        # THRESHOLD_MONEY = 50 * (tool.trade_time_sub(tool.get_now_time_str(), "09:30:00") // 60) + 1000
+        # THRESHOLD_MONEY = min(THRESHOLD_MONEY, 10000)
+        # THRESHOLD_MONEY = max(THRESHOLD_MONEY, 1000)
+        # THRESHOLD_MONEY = THRESHOLD_MONEY * 10000
+        THRESHOLD_MONEY = 0
+        # 鏈�澶ф暟閲�
+        # MAX_COUNT = cls.get_jingxuan_in_block_threshold_count()
+
+        cls.top_in_list_cache = datas
+        blocks = set()
+        count = 0
+        fblock_money = {}
+        for data in datas:
+            cls.__jx_blocks_in_money_dict[data[1]] = data[3]
+            if data[1] in constant.KPL_INVALID_BLOCKS:
+                continue
+            if data[3] < THRESHOLD_MONEY:
+                continue
+            # 杩囨护鍑烘潵涓哄悓涓�涓澘鍧楀氨鍙畻1涓暟閲�
+            fb = BlockMapManager().filter_blocks({data[1]})
+            if blocks & fb:
+                continue
+
+            for b in fb:
+                fblock_money[b] = data[3]
+            blocks |= fb
+
+            # 濡傛灉璇ュ師鍥犳病鏈夋定鍋滅エ瑕佸線鍚庣Щ涓�浣�
+            has_code = False
+            for b in fb:
+                if ContainsLimitupCodesBlocksManager().get_block_codes(b):
+                    has_code = True
+                    break
+            if has_code:
+                count += 1
+                if count == 10:
+                    strong = cls.get_market_strong()
+                    if strong is None:
+                        strong = 60
+                    if data[3] > 3e7:
+                        # 澶т簬3鍗冧竾
+                        THRESHOLD_MONEY = int((1 - strong / 200) * data[3])
+                    else:
+                        THRESHOLD_MONEY = data[3]
+            # if count >= MAX_COUNT:
+            #     break
+        # 璁板綍绮鹃�夋祦鍑烘棩蹇�
+        async_log_util.info(logger_kpl_jx_in, f"鍘熸暟鎹細{datas[:50]} 鏉垮潡锛歿blocks}")
+        blocks = list(blocks)
+        blocks.sort(key=lambda x: fblock_money.get(x), reverse=True)
+        cls.__top_jx_blocks = blocks
+
+    @classmethod
+    def set_market_jingxuan_out_blocks(cls, datas):
+        """
+        璁剧疆绮鹃�夋祦鍑烘暟鎹�
+        @param datas:
+        @return:
+        """
+        cls.top_out_list_cache = datas
+        count = 0
+        blocks = set()
+        for data in datas:
+            cls.__jx_blocks_in_money_dict[data[1]] = data[3]
+            if data[1] in constant.KPL_INVALID_BLOCKS:
+                continue
+            if data[3] > -5e7:
+                # 杩囨护5鍗冧竾浠ヤ笂鐨�
+                break
+            # 杩囨护鍑烘潵涓哄悓涓�涓澘鍧楀氨鍙畻1涓暟閲�
+            fb = BlockMapManager().filter_blocks({data[1]})
+            if blocks & fb:
+                continue
+            blocks |= fb
+            count += 1
+            if count >= 10:
+                break
+        # 璁板綍绮鹃�夋祦鍑烘棩蹇�
+        async_log_util.info(logger_kpl_jx_out, f"鍘熸暟鎹細{datas[:10]} 鏉垮潡锛歿blocks}")
+        cls.__top_jx_out_blocks = list(blocks)
+
+    @classmethod
+    def set_market_strong(cls, strong):
+        """
+        璁剧疆甯傚満琛屾儏寮哄害
+        @param strong:
+        @return:
+        """
+        cls.__market_strong = strong
+
+    @classmethod
+    def is_ignore_block_in_money(cls):
+        if cls.__market_strong and cls.__market_strong >= constant.IGNORE_BLOCK_IN_MONEY_MARKET_STRONG:
+            return True
+        return False
+
+    @classmethod
+    def get_market_strong(cls):
+        return cls.__market_strong
+
+    @classmethod
+    def get_top_market_jingxuan_blocks(cls):
+        return cls.__top_jx_blocks
+
+    @classmethod
+    def get_top_market_jingxuan_out_blocks(cls):
+        return cls.__top_jx_out_blocks
+
+    @classmethod
+    def get_block_info_at_block_in(cls, b):
+        """
+        鑾峰彇鏉垮潡鐨勫噣娴佸叆鎯呭喌
+        @param b:
+        @return: (鏉垮潡鍚嶇О,韬綅,娴佸叆閲戦)
+        """
+        for i in range(0, len(cls.top_in_list_cache)):
+            if cls.top_in_list_cache[i][1] == b:
+                return b, i, cls.top_in_list_cache[i][3]
+        return b, -1, 0
 
     @classmethod
     def set_top_5_industry(cls, datas):
@@ -251,47 +683,20 @@
         temp_set = cls.top_5_key_dict.keys()
         return temp_set
 
-    # 閫氳繃鍏抽敭瀛楀垽鏂兘涔扮殑浠g爜鏁伴噺
-    @classmethod
-    def get_can_buy_codes_count(cls, code, key):
-        # 鍒ゆ柇琛屼笟娑ㄥ仠绁ㄦ暟閲忥紝闄ゅ紑鑷繁蹇呴』澶т簬1涓�
-        temp_codes = LimitUpCodesPlateKeyManager.total_key_codes_dict.get(key)
-        if temp_codes is None:
-            temp_codes = set()
-        else:
-            temp_codes = set(temp_codes)
-        temp_codes.discard(code)
-        if len(temp_codes) < 1:
-            # 鍚庢帓鎵嶈兘鎸傚崟
-            return 0, "韬綅涓嶄负鍚庢帓"
-
-        forbidden_plates = cls.__KPLPlateForbiddenManager.list_all_cache()
-        if key in forbidden_plates:
-            return 0, "涓嶄拱璇ユ澘鍧�"
-
-        # 10:30浠ュ墠鍙互鎸�2涓崟
-        if int(tool.get_now_time_str().replace(':', '')) < int("100000"):
-            return 2, "10:00浠ュ墠鍙互鎸�2涓崟"
-        # 10:30浠ュ悗
-        if key not in cls.top_5_key_dict:
-            return 0, "鍑�娴佸叆娌″湪鍓�5"
-        if cls.top_5_key_dict[key][1] > 3 * 10000 * 10000:
-            return 2, "鍑�娴佸叆鍦ㄥ墠5涓斿ぇ浜�3浜�"
-        else:
-            return 1, "鍑�娴佸叆鍦ㄥ墠5"
-
     @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_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:
             return False, None
+
+    @classmethod
+    def get_jx_block_in_money(cls, block):
+        return cls.__jx_blocks_in_money_dict.get(block)
 
 
 # 浠g爜鍘嗗彶娑ㄥ仠鍘熷洜涓庢澘鍧楃鐞�
@@ -302,6 +707,14 @@
     # 鏉垮潡
     __blocks_dict = {}
 
+    __instance = None
+
+    def __new__(cls, *args, **kwargs):
+        if not cls.__instance:
+            cls.__instance = super(CodesHisReasonAndBlocksManager, cls).__new__(cls, *args, **kwargs)
+
+        return cls.__instance
+
     def __get_redis(self):
         return self.__redisManager.getRedis()
 
@@ -309,7 +722,6 @@
         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}")
 
     # 濡傛灉杩斿洖鍊间笉涓篘one琛ㄧず宸茬粡鍔犺浇杩囧巻鍙插師鍥犱簡
     def get_history_limit_up_reason(self, code):
@@ -359,6 +771,41 @@
             blocks = set()
         return reasons | blocks
 
+    __history_blocks_dict_cache = {}
+
+    def get_history_blocks(self, code):
+        """
+        鑾峰彇180澶╃殑鍘嗗彶娑ㄥ仠鍘熷洜
+        @param code:
+        @return:
+        """
+        if code in self.__history_blocks_dict_cache:
+            return self.__history_blocks_dict_cache.get(code)
+        try:
+            kpl_results = KPLLimitUpDataUtil.get_latest_block_infos(code=code)
+            # 鍙栨渶杩�2鏉℃暟鎹�
+            if kpl_results and len(kpl_results) > 2:
+                kpl_results = kpl_results[-2:]
+            keys = set()
+            if kpl_results:
+                keys |= set([x[2] for x in kpl_results])
+            for r in kpl_results:
+                if r[3]:
+                    keys |= set(r[3].split("銆�"))
+            self.__history_blocks_dict_cache[code] = keys
+            return keys
+        except:
+            pass
+        return set()
+
+    def get_history_blocks_cache(self, code):
+        """
+        鑾峰彇180澶╃殑鍘嗗彶娑ㄥ仠鍘熷洜缂撳瓨
+        @param code:
+        @return:
+        """
+        return self.__history_blocks_dict_cache.get(code)
+
 
 # 鐩爣浠g爜鏉垮潡鍏抽敭璇嶇鐞�
 class TargetCodePlateKeyManager:
@@ -370,35 +817,54 @@
         return self.__redisManager.getRedis()
 
     # 杩斿洖key闆嗗悎(鎺掗櫎鏃犳晥鏉垮潡),浠婃棩娑ㄥ仠鍘熷洜,浠婃棩鍘嗗彶娑ㄥ仠鍘熷洜,鍘嗗彶娑ㄥ仠鍘熷洜,浜岀骇,绮鹃�夋澘鍧�
-    def get_plate_keys(self, code):
+    def get_plate_keys(self, code, contains_today=True):
+        """
+        鑾峰彇浠g爜鐨勬澘鍧�: 锛�180澶╃殑娑ㄥ仠鍘熷洜+鎺ㄨ崘鍘熷洜锛�+浠婃棩娑ㄥ仠鍘熷洜+浠婃棩娑ㄥ仠鎺ㄨ崘鍘熷洜+浠婃棩鎺ㄨ崘鍘熷洜
+        @param code:
+        @return: 锛堟澘鍧楀叧閿瘝闆嗗悎,浠婃棩娑ㄥ仠鍘熷洜+娑ㄥ仠鎺ㄨ崘鍘熷洜,浠婃棩鍘嗗彶娑ㄥ仠鍘熷洜,鍘嗗彶娑ㄥ仠鍘熷洜,绮鹃�夋澘鍧楋級
+        """
         keys = set()
         k1 = set()
-        if code in LimitUpCodesPlateKeyManager.today_total_limit_up_reason_dict:
-            k1 = {LimitUpCodesPlateKeyManager.today_total_limit_up_reason_dict[code]}
+
+        limit_up_reason_info = LimitUpCodesPlateKeyManager.get_today_limit_up_reason(code)
+        if limit_up_reason_info:
+            k1 = {limit_up_reason_info[0]} | set(limit_up_reason_info[1])
         # 鍔犺浇浠婃棩鍘嗗彶鍘熷洜,鏆傛椂涓嶉渶瑕佸巻鍙插師鍥犱簡
         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()
-        industry = global_util.code_industry_map.get(code)
-        if industry:
-            k3 = {industry}
+
+        k3 = self.__CodesPlateKeysManager.get_history_blocks(code)
+        if k3:
+            keys |= k3
+        # industry = global_util.code_industry_map.get(code)
+        # if industry:
+        #     k3 = {industry}
 
         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
+        jingxuan_block_info = self.__KPLCodeJXBlockManager.get_jx_blocks_cache(code)
+        if not jingxuan_block_info:
+            jingxuan_block_info = self.__KPLCodeJXBlockManager.get_jx_blocks_cache(code, by=True)
+        if jingxuan_block_info:
+            jingxuan_blocks = jingxuan_block_info[0]
+            k4 |= set(jingxuan_blocks)  # set([x[1] for x in jingxuan_blocks])
+        if k1 and contains_today:
+            # 娑ㄥ仠杩�
+            keys |= k1
 
-        # 鎺掗櫎鏃犳晥鐨勬定鍋滃師鍥�
+        # 鑾峰彇涓嶅埌娑ㄥ仠鍘熷洜
+        if contains_today:
+            keys |= k4
         keys = keys - set(constant.KPL_INVALID_BLOCKS)
-
         return keys, k1, k11, k2, k3, k4
+
+    def get_plate_keys_for_radical_buy(self, code):
+        """
+        婵�杩涗拱鍏ョ殑鏉垮潡
+        @param code:
+        @return:
+        """
 
 
 class CodePlateKeyBuyManager:
@@ -416,58 +882,262 @@
     __TargetCodePlateKeyManager = TargetCodePlateKeyManager()
     __LimitUpCodesPlateKeyManager = LimitUpCodesPlateKeyManager()
     __CodesHisReasonAndBlocksManager = CodesHisReasonAndBlocksManager()
-    __CodesTradeStateManager = trade_manager.CodesTradeStateManager()
     __can_buy_compute_result_dict = {}
 
+    # 鏄惁闇�瑕佺Н鏋佷拱
     @classmethod
-    def __remove_from_l2(cls, code, msg):
-        # 涓嬭繃鍗曠殑浠g爜涓嶇Щ闄�
-        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)
+    def __is_need_active_buy(cls, code, block, current_rank, open_limit_up_count):
+        """
+        鏉垮潡鏄惁闇�瑕佺Н鏋佷拱鍏�
+        瑙勫垯锛氭牴鎹韩浣嶅垽鏂槸鍚﹂渶瑕佺Н鏋佷拱锛屾牴鎹椂闂村垝鍒�
+        @param code: 浠g爜
+        @param block: 鏉垮潡鍚嶇О
+        @param current_rank: 鐩墠鍦ㄦ澘鍧椾腑鐨勮韩浣嶏紝浠�0寮�濮�
+        @param open_limit_up_count: 寮�1鐨勬暟閲�
+        @return:
+        """
 
+        real_current_rank = max(current_rank - open_limit_up_count, 0)
+
+        TIME_STR_RANGES = ["10:00:00", "10:30:00", "11:00:00", "13:00:00", "13:30:00", "14:00:00", "14:30:00",
+                           "15:00:00"]
+        TIME_INT_RANGES = [int(x.replace(':', '')) for x in TIME_STR_RANGES]
+        MAX_RANKS = [3, 3, 2, 2, 1, 0, 0, 0]
+        now_time_str = tool.get_now_time_str().replace(':', '')
+        for i in range(len(TIME_INT_RANGES)):
+            if int(now_time_str) <= TIME_INT_RANGES[i]:
+                if MAX_RANKS[i] > real_current_rank:
+                    return True
+                break
+        return False
+
+    # 杩斿洖鍐呭(鏄惁鍙拱, 鏄惁涓虹嫭鑻�, 鎻忚堪淇℃伅, 鏄惁涓哄己鍔夸富绾�, 鏄惁闇�瑕佺Н鏋佷拱)
     @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)})")
+    def __is_block_can_buy(cls, code, block, current_limit_up_datas, code_limit_up_reasons_dict,
+                           yesterday_current_limit_up_codes, limit_up_record_datas, current_limit_up_block_codes_dict,
+                           high_level_code_blocks=None, high_level_block_codes=None):
+        # 鐙嫍鍒ゆ柇
+        if high_level_code_blocks is None:
+            high_level_code_blocks = {}
+        if high_level_block_codes is None:
+            high_level_block_codes = {}
+        block_codes = current_limit_up_block_codes_dict.get(block)
+        if block_codes is None:
+            block_codes = set()
+
+        if not block_codes:
+            # 楂樹綅鏉挎硾鍖栨澘鍧椾腑鏃犳澘鍧�
+            if not high_level_block_codes.get(block):
+                return False, True, f"銆恵block}銆�:鏉垮潡鏃犳定鍋�", False, False
+        elif len(block_codes) == 1 and code in block_codes:
+            if not high_level_block_codes.get(block):
+                return False, True, f"{block}:鏉垮潡鍙湁褰撳墠浠g爜娑ㄥ仠", False, False
+        # 鍙互涔扮殑鏈�澶ф帓鍚�
+        # open_limit_up_codes = kpl_block_util.get_shsz_open_limit_up_codes(code, block, limit_up_record_datas,
+        #                                                                   code_limit_up_reason_dict)
+        current_open_limit_up_codes = kpl_block_util.get_shsz_open_limit_up_codes_current(code, block,
+                                                                                          current_limit_up_datas)
+
+        # ---------------------------鍒ゆ柇寮哄娍涓荤嚎-------------------------
+        is_strong_block = False
+        for d in current_limit_up_datas:
+            bs = kpl_util.get_current_limit_up_reasons(d)
+            if block not in bs:
+                general_blocks = high_level_code_blocks.get(d[0])
+                if not general_blocks or block not in general_blocks:
+                    # 娌″湪娉涘寲鏉垮潡涓�
+                    continue
+            count = kpl_util.get_high_level_count(d[4])
+            if count >= 3:
+                if d[4].find("杩炴澘") > 0:
+                    is_strong_block = True
+                    break
+                elif d[0] in yesterday_current_limit_up_codes and len(block_codes) >= 2:
+                    # 鍑犲ぉ鍑犳澘锛屼笖鏈�杩�2杩炴澘
+                    # 鐪嬫槸鍚︽湁棣栨澘鍚庢帓
+                    is_strong_block = True
+                    break
+
+        if not is_strong_block:
+            temp_block_codes = set(copy.deepcopy(block_codes))
+            temp_block_codes.discard(code)
+            if len(temp_block_codes) >= 3:
+                is_strong_block = True
+        max_rank = 2
+        #  寮哄娍鏉垮潡涔拌�佸洓
+        if is_strong_block:
+            max_rank = 3
+
+        # 闇�瑕佹帓闄ょ殑鑰佸ぇ鐨勪唬鐮�
+        exclude_first_codes = set()  # HighIncreaseCodeManager().list_all()
+
+        # 鑾峰彇涓绘澘寮�1鐨勪唬鐮�
+
+        # 鍓旈櫎楂樹綅鏉�
+        if current_open_limit_up_codes and yesterday_current_limit_up_codes:
+            current_open_limit_up_codes -= yesterday_current_limit_up_codes
+
+        # 鑾峰彇浠g爜鐨勫垵娆℃定鍋滄椂闂�
+        first_limit_up_time = time.time()
+        # if limit_up_record_datas:
+        for r in limit_up_record_datas:
+            if r[3] == code:
+                first_limit_up_time = int(r[5])
 
         # 鑾峰彇涓绘澘瀹炴椂韬綅,鍓旈櫎楂樹綅鏉�
-        current_shsz_rank = 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 = 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)
-        # 鑾峰彇涓绘澘鍘嗗彶韬綅
+        current_shsz_rank, front_current_shsz_rank_codes = kpl_block_util.get_code_current_rank(code, block,
+                                                                                                current_limit_up_datas,
+                                                                                                code_limit_up_reasons_dict,
+                                                                                                yesterday_current_limit_up_codes,
+                                                                                                exclude_first_codes,
+                                                                                                len(
+                                                                                                    current_open_limit_up_codes),
+                                                                                                shsz=True,
+                                                                                                limit_up_time=first_limit_up_time)
+        # 璁$畻鏄惁闇�瑕佺Н鏋佷拱鍏�
+        is_active_buy = cls.__is_need_active_buy(code, block, current_shsz_rank, len(current_open_limit_up_codes))
 
-        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
-                return True, f"{tool.get_now_time_str()} {block}锛歵op10娑ㄥ仠鏉垮潡锛屼富鏉垮紑1({pen_limit_up_codes}),灞炰簬涓绘澘鍓嶉緳{len(pen_limit_up_codes) + 1}(瀹炴椂韬綅-{current_shsz_rank}/{len(current_limit_up_datas)})"
-            else:
-                if record_shsz_rank >= len(pen_limit_up_codes) + 1:
-                    cls.__remove_from_l2(code, f"{code}鏍规嵁韬綅绂佹涔板叆锛氥�恵block}銆戝巻鍙茶韩浣峽record_shsz_rank}")
-                return False, f"鏉垮潡-{block}: top4娑ㄥ仠鏉垮潡锛屼富鏉垮紑1锛坽pen_limit_up_codes}锛�,涓嶄负涓绘澘鍓嶉緳{len(pen_limit_up_codes) + 1}锛堝疄鏃惰韩浣�-{current_shsz_rank},鍘嗗彶韬綅-{record_shsz_rank}锛�"
+        # 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)
+        if int(tool.get_now_time_str().replace(":", "")) <= int("094000") and is_strong_block:
+            # 寮哄娍涓荤嚎鍔犲己鍔�10鍒嗛挓
+            return True, False, f"銆恵block}銆戯細寮哄娍涓荤嚎+寮哄娍10鍒嗛挓", is_strong_block, is_active_buy
+
+        if current_shsz_rank < len(current_open_limit_up_codes) + max_rank:
+            return True, False, f"銆恵block}銆戝墠鎺掍唬鐮侊細{current_shsz_rank}", is_strong_block, is_active_buy
         else:
-            if current_shsz_rank == 0 and record_shsz_rank < 2:
-                return True, f"{tool.get_now_time_str()} {block}锛歵op4娑ㄥ仠鏉垮潡锛岄潪涓绘澘寮�1锛屽睘浜庨緳1锛屽疄鏃舵定鍋滃垪琛ㄦ暟閲�({len(current_limit_up_datas)})"
-            else:
-                if record_shsz_rank >= 2:
-                    cls.__remove_from_l2(code, f"{code}鏍规嵁韬綅绂佹涔板叆锛氥�恵block}銆戝巻鍙茶韩浣峽record_shsz_rank}")
+            # k_format = code_nature_analyse.CodeNatureRecordManager().get_k_format_cache(code)
+            # if k_format and k_format[8][0]:
+            #     # 鍏锋湁杈ㄨ瘑搴�
+            #     return True, False, f"銆恵block}銆戝叿鏈夎鲸璇嗗害", is_strong_block
+            # 鐪嬭嚜鐢辨祦閫氬競鍊兼槸鍚﹀皬浜�20浜�
+            if is_strong_block and current_shsz_rank < len(current_open_limit_up_codes) + max_rank + 1:
+                zyltgb_as_yi = round(global_util.zyltgb_map.get(code) / 100000000,
+                                     2) if code in global_util.zyltgb_map else None
+                situation = MarketSituationManager().get_situation_cache()
+                zylt_threshold_as_yi = buy_condition_util.get_zyltgb_threshold(situation)
+                if zyltgb_as_yi and zylt_threshold_as_yi[2] <= zyltgb_as_yi <= zylt_threshold_as_yi[3]:
+                    return True, False, f"銆恵block}銆戝己鍔挎澘鍧� 鑷敱娴侀�氬競鍊�({zyltgb_as_yi})澶т簬{zylt_threshold_as_yi[2]}浜� 灏忎簬{zylt_threshold_as_yi[3]}浜�", is_strong_block, is_active_buy
+            return False, False, f"銆恵block}銆戝墠鎺掍唬鐮侊細{front_current_shsz_rank_codes} 瓒呰繃{len(current_open_limit_up_codes) + max_rank}涓�", is_strong_block, is_active_buy
 
-                return False, f"鏉垮潡-{block}: top4娑ㄥ仠鏉垮潡锛岄潪涓绘澘寮�1,涓嶄负涓绘澘榫�1锛堝疄鏃惰韩浣�-{current_shsz_rank},鍘嗗彶韬綅-{record_shsz_rank}锛�"
+        # 杩囨椂鐨勪唬鐮�
+        # 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}锛歵op10娑ㄥ仠鏉垮潡锛屼富鏉垮紑1({open_limit_up_codes}),灞炰簬涓绘澘鍓嶉緳{len(open_limit_up_codes) + 1}(瀹炴椂韬綅-{current_shsz_rank}:{front_current_shsz_rank_codes}/{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}锛歵op4娑ㄥ仠鏉垮潡锛岄潪涓绘澘寮�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}锛�"
+
+    @classmethod
+    def __is_block_can_buy_new(cls, code, block, current_limit_up_datas, code_limit_up_reasons_dict,
+                               yesterday_current_limit_up_codes, limit_up_record_datas,
+                               current_limit_up_block_codes_dict,
+                               high_level_code_blocks=None, high_level_block_codes=None):
+        """
+        璇ョエ鐨勬澘鍧楁槸鍚﹀彲浠ヤ拱
+        @param code:
+        @param block:
+        @param current_limit_up_datas:
+        @param code_limit_up_reasons_dict:
+        @param yesterday_current_limit_up_codes:
+        @param limit_up_record_datas:
+        @param current_limit_up_block_codes_dict:
+        @param high_level_code_blocks:
+        @param high_level_block_codes:
+        @return:
+        """
+        # 鐙嫍鍒ゆ柇
+        if high_level_code_blocks is None:
+            high_level_code_blocks = {}
+        if high_level_block_codes is None:
+            high_level_block_codes = {}
+        block_codes = current_limit_up_block_codes_dict.get(block)
+        if block_codes is None:
+            block_codes = set()
+        # 鍘嗗彶娑ㄥ仠浠g爜
+        block_codes_records = set()
+        if limit_up_record_datas:
+            for k in limit_up_record_datas:
+                if block in code_limit_up_reasons_dict.get(k[3]):
+                    block_codes_records.add(k[3])
+
+        if not block_codes:
+            # 楂樹綅鏉挎硾鍖栨澘鍧椾腑鏃犳澘鍧�
+            if not high_level_block_codes.get(block):
+                return False, True, f"銆恵block}銆�:鏉垮潡鏃犳定鍋�", False, False, 0, 0, 0
+        elif len(block_codes) == 1 and code in block_codes:
+            if not high_level_block_codes.get(block):
+                return False, True, f"{block}:鏉垮潡鍙湁褰撳墠浠g爜娑ㄥ仠", False, False, 0, 0, 0
+        # 鍙互涔扮殑鏈�澶ф帓鍚�
+        # open_limit_up_codes = kpl_block_util.get_shsz_open_limit_up_codes(code, block, limit_up_record_datas,
+        #                                                                   code_limit_up_reason_dict)
+        current_open_limit_up_codes = kpl_block_util.get_shsz_open_limit_up_codes_current(code, block,
+                                                                                          current_limit_up_datas)
+
+        is_strong_block = False
+
+        # 鏈�澶氫拱鑰佸嚑
+        RANKS = [6, 5, 4, 4, 3, 3, 2]
+        RANK_TIMES = ["10:00:00", "10:30:00", "11:00:00", "11:30:00", "13:30:00", "14:00:00", "15:00:00"]
+        now_time_str = tool.get_now_time_str()
+        max_rank = 2
+        for i in range(len(RANK_TIMES)):
+            if tool.trade_time_sub(now_time_str, RANK_TIMES[i]) <= 0:
+                max_rank = RANKS[i]
+                break
+
+        # 闇�瑕佹帓闄ょ殑鑰佸ぇ鐨勪唬鐮�
+        exclude_first_codes = set()
+
+        # 鑾峰彇涓绘澘寮�1鐨勪唬鐮�
+
+        # 鍓旈櫎楂樹綅鏉�
+        if current_open_limit_up_codes and yesterday_current_limit_up_codes:
+            current_open_limit_up_codes -= yesterday_current_limit_up_codes
+
+        # 鑾峰彇浠g爜鐨勫垵娆℃定鍋滄椂闂�
+        first_limit_up_time = time.time()
+        # if limit_up_record_datas:
+        for r in limit_up_record_datas:
+            if r[3] == code:
+                first_limit_up_time = int(r[5])
+
+        # 鑾峰彇涓绘澘瀹炴椂韬綅,鍓旈櫎楂樹綅鏉�
+        current_shsz_rank, front_current_shsz_rank_codes = kpl_block_util.get_code_current_rank(code, block,
+                                                                                                current_limit_up_datas,
+                                                                                                code_limit_up_reasons_dict,
+                                                                                                yesterday_current_limit_up_codes,
+                                                                                                exclude_first_codes,
+                                                                                                len(
+                                                                                                    current_open_limit_up_codes),
+                                                                                                shsz=True,
+                                                                                                limit_up_time=first_limit_up_time)
+
+        # 璁$畻鏄惁闇�瑕佺Н鏋佷拱鍏�
+        is_active_buy = cls.__is_need_active_buy(code, block, current_shsz_rank, len(current_open_limit_up_codes))
+
+        if current_shsz_rank < len(current_open_limit_up_codes) + max_rank:
+            return True, len(block_codes | {
+                code}) <= 1, f"銆恵block}銆戝墠鎺掍唬鐮侊細{current_shsz_rank}", is_strong_block, is_active_buy, current_shsz_rank, len(
+                block_codes), len(block_codes_records)
+        else:
+            return False, len(block_codes | {
+                code}) <= 1, f"銆恵block}銆戝墠鎺掍唬鐮侊細{front_current_shsz_rank_codes} 瓒呰繃{len(current_open_limit_up_codes) + max_rank}涓�", is_strong_block, is_active_buy, current_shsz_rank, len(
+                block_codes), len(block_codes_records)
 
     # 鑾峰彇鍙互涔扮殑鏉垮潡
     # current_limit_up_datas: 浠婃棩瀹炴椂娑ㄥ仠
@@ -475,100 +1145,113 @@
     # limit_up_record_datas锛氫粖鏃ュ巻鍙叉定鍋�
     # yesterday_current_limit_up_codes 锛� 鏄ㄦ棩娑ㄥ仠浠g爜
     # before_blocks_dict锛氬巻鍙叉定鍋滃師鍥�
+    # 杩斿洖鏉垮潡鐨勮绠楃粨鏋淸(鏉垮潡鍚嶇О,鏄惁鍙拱,鏄惁鏄嫭鑻�,淇℃伅)]
+
     @classmethod
     def get_can_buy_block(cls, code, current_limit_up_datas, limit_up_record_datas, yesterday_current_limit_up_codes,
-                          before_blocks_dict):
+                          before_blocks_dict, current_limit_up_block_codes_dict, high_level_general_code_blocks,
+                          high_level_general_block_codes):
         # 鍔犺浇娑ㄥ仠浠g爜鐨勭洰鏍囨澘鍧�
         def load_code_block():
-            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 limit_up_record_datas:
+                # 鑾峰彇浠婃棩9:30浠ュ墠鐨勬椂闂�
+                time_str = datetime.datetime.now().strftime("%Y-%m-%d") + " 09:30:00"
+                timestamp = time.mktime(time.strptime(time_str, '%Y-%m-%d %H:%M:%S'))
+
+                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_reasons_dict[d[3]] = {list(before_blocks_dict.get(d[3]))[0]}
+                    else:
+                        code_limit_up_reasons_dict[d[3]] = {d[2]}
+                        # 寮�1鎵嶈兘鍖呭惈鎺ㄨ崘鍘熷洜
+                        if d[6] and int(d[5]) < timestamp:
+                            code_limit_up_reasons_dict[d[3]] |= set(d[6].split("銆�"))
+            return code_limit_up_reasons_dict
 
         if current_limit_up_datas is None:
             current_limit_up_datas = []
 
         # 鑾峰彇鐩爣浠g爜鏉垮潡
-        keys, k1, k11, k2, k3, k4 = cls.__TargetCodePlateKeyManager.get_plate_keys(code)
-        log.logger_kpl_debug.info("{}鍏抽敭璇嶏細浠婃棩-{},浠婃棩鍘嗗彶-{},鍘嗗彶-{},浜岀骇琛屼笟-{},浠g爜鏉垮潡-{}", 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 True:
-            # 鑾峰彇
-            if k4:
-                keys |= k4
-                keys = keys - constant.KPL_INVALID_BLOCKS
+        # keys, k1, k11, k2, k3, k4 = cls.__TargetCodePlateKeyManager.get_plate_keys(code)
+        keys = LimitUpCodesBlockRecordManager().get_radical_buy_blocks(code)
+        if not keys:
+            keys = set()
+        keys = BlockMapManager().filter_blocks(keys)
+        if keys:
+            keys -= constant.KPL_INVALID_BLOCKS
 
-        log.logger_kpl_debug.info("{}鏈�缁堝叧閿瘝锛歿}", code, keys)
+        # log.logger_kpl_debug.info("{}鏈�缁堝叧閿瘝锛歿}", code, keys)
 
         # 娑ㄥ仠鍒楄〃涓尮閰嶅叧閿瘝锛岃繑鍥烇紙鏉垮潡:浠g爜闆嗗悎锛夛紝浠g爜闆嗗悎涓凡缁忔帓闄よ嚜韬�
+
+        fresults = []
         if not keys:
-            return None, "灏氭湭鎵惧埌娑ㄥ仠鍘熷洜"
-        code_limit_up_reason_dict = {}
+            return fresults, set()
+
+        code_limit_up_reasons_dict = {}
         load_code_block()
-        msg_list = []
-
-        can_buy_blocks = []
         for block in keys:
-
-            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:
-                msg_list.append(msg)
-        if len(can_buy_blocks) == len(keys):
-            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
-
-        return None, "\n".join(msg_list)
+            can_buy, unique, msg, is_strong, is_active_buy, current_rank, block_limit_up_count, block_limit_up_record_count = cls.__is_block_can_buy_new(
+                code, block,
+                current_limit_up_datas,
+                code_limit_up_reasons_dict,
+                yesterday_current_limit_up_codes,
+                limit_up_record_datas,
+                current_limit_up_block_codes_dict,
+                high_level_code_blocks=high_level_general_code_blocks,
+                high_level_block_codes=high_level_general_block_codes)
+            fresults.append((block, can_buy, unique, msg, is_strong, is_active_buy, current_rank, block_limit_up_count,
+                             block_limit_up_record_count))
+        return fresults, keys
 
     # 鏄惁鍙互涓嬪崟
-    # 杩斿洖锛氭槸鍚﹀彲浠ヤ笅鍗�,娑堟伅,鏉垮潡绫诲瀷
+    # 杩斿洖锛氬彲浠ヤ拱鐨勬澘鍧�,鏄惁鐙嫍,娑堟伅
+    #  鍙拱鐨勬澘鍧�, 鏄惁鐙嫍, 娑堟伅, 鍙拱鐨勫己鍔挎澘鍧�, 鍏抽敭璇�, 绉瀬涔扮殑鏉垮潡
     @classmethod
     def can_buy(cls, code):
         if constant.TEST:
-            return True, cls.BLOCK_TYPE_NONE
-        if True:
-            # 娴嬭瘯
-            return True, "涓嶅垽鏂澘鍧楄韩浣�"
+            return [("娴嬭瘯", 0, 1, 1)], True, cls.BLOCK_TYPE_NONE, [], set(), ["鍖栧伐"]
+        # if True:
+        #     # 娴嬭瘯
+        #     return True, "涓嶅垽鏂澘鍧楄韩浣�"
         return cls.__can_buy_compute_result_dict.get(code)
 
+    # 杩斿洖:(鍙互涔扮殑鏉垮潡鍒楄〃, 鏄惁鏄嫭鑻�, 娑堟伅绠�浠�,鍙拱鐨勫己鍔夸富绾�, 绉瀬涔板叆鏉垮潡鍒楄〃)
     @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
-        log.logger_kpl_debug.info(f"{code}:鑾峰彇濮旀墭/涔板叆浠g爜")
-        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(cls.__CodesTradeStateManager.get_codes_by_trade_states_cache(
-            {trade_manager.TRADE_STATE_BUY_SUCCESS}))
+                                 yesterday_current_limit_up_codes, before_blocks_dict,
+                                 current_limit_up_block_codes_dict, high_level_general_code_blocks, codes_delegate,
+                                 codes_success):
+        # 鏍规嵁浠g爜娉涘寲鏉垮潡鑾峰彇娉涘寲鏉垮潡鐨勪唬鐮侀泦鍚�
+        high_level_general_block_codes = {}
+        for c in high_level_general_code_blocks:
+            blocks = high_level_general_code_blocks[c]
+            for b in blocks:
+                if b not in high_level_general_block_codes:
+                    high_level_general_block_codes[b] = set()
+                high_level_general_block_codes[b].add(c)
+        blocks_compute_results, keys = cls.get_can_buy_block(code, current_limit_up_datas,
+                                                             limit_up_record_datas, yesterday_current_limit_up_codes,
+                                                             before_blocks_dict, current_limit_up_block_codes_dict,
+                                                             high_level_general_code_blocks,
+                                                             high_level_general_block_codes)
+        if not blocks_compute_results:
+            return False, True, f"娌℃湁鎵惧埌鏉垮潡", [], keys, []
 
         codes = codes_delegate | codes_success
-
         # 缁熻鎴愪氦浠g爜鐨勬澘鍧�
         trade_codes_blocks_dict = {}
         # 宸茬粡鎴愪氦鐨勬澘鍧�
         trade_success_blocks_count = {}
-        log.logger_kpl_debug.info(f"{code}:鑾峰彇浠g爜鏉垮潡")
+        trade_delegate_blocks_count = {}
         for c in codes:
             keys_, k1_, k11_, k2_, k3_, k4_ = cls.__TargetCodePlateKeyManager.get_plate_keys(c)
-            # 瀹炴椂娑ㄥ仠鍘熷洜
-            trade_codes_blocks_dict[c] = k1_ | k4_
+            # 瀹炴椂娑ㄥ仠鍘熷洜 + 鎺ㄨ崘鍘熷洜
+            if not k1_:
+                trade_codes_blocks_dict[c] = k4_
+            else:
+                trade_codes_blocks_dict[c] = k1_
         # 缁熻鏉垮潡涓殑浠g爜
-        log.logger_kpl_debug.info(f"{code}:缁熻鏉垮潡涓殑浠g爜")
         trade_block_codes_dict = {}
         for c in trade_codes_blocks_dict:
             for b in trade_codes_blocks_dict[c]:
@@ -576,73 +1259,104 @@
                     if b not in trade_success_blocks_count:
                         trade_success_blocks_count[b] = set()
                     trade_success_blocks_count[b].add(c)
+                if c in codes_delegate:
+                    if b not in trade_delegate_blocks_count:
+                        trade_delegate_blocks_count[b] = set()
+                    trade_delegate_blocks_count[b].add(c)
+
                 if b not in trade_block_codes_dict:
                     trade_block_codes_dict[b] = set()
                 trade_block_codes_dict[b].add(c)
 
         # ---------------------------------鍔犺浇宸茬粡涓嬪崟/鎴愪氦鐨勪唬鐮佷俊鎭�------------end-------------
-        log.logger_kpl_debug.info(f"{code}:寮�濮嬭绠楁槸鍚﹀彲浠ヤ拱")
-        msg_list = []
-        for key in blocks:
-            # 鏉垮潡涓凡缁忔湁鎴愪氦鐨勫氨涓嶄笅鍗曚簡
-            if key in trade_success_blocks_count:
-                success_codes_count = len(trade_success_blocks_count[key])
-                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
 
-        return False, ",".join(msg_list)
+        #
+        can_buy_blocks = []
+        can_buy_strong_blocks = []
+        unique_count = 0
+        msg_list = []
+        active_buy_blocks = []
+        for r in blocks_compute_results:
+            # r鐨勬暟鎹粨鏋�(鏉垮潡,鏄惁鍙互涔�,鏄惁鐙嫍,娑堟伅,鏄惁鏄己鍔挎澘鍧�, 绉瀬涔板叆淇℃伅)
+            if r[2]:
+                # 鐙嫍
+                unique_count += 1
+            if r[1]:
+                # 寮哄娍涓荤嚎鏈�澶氬悓鏃舵寕3鍙エ锛屾渶澶氭垚浜�2鍙エ
+                MAX_DELEGATE_COUNT = 3 if r[4] else 2
+                MAX_DEAL_COUNT = 2 if r[4] else 1
+                # if r[0] in trade_success_blocks_count and len(trade_success_blocks_count[r[0]]) >= MAX_DEAL_COUNT:
+                #     msg_list.append(f"銆恵r[0]}銆戞湁鎴愪氦浠g爜锛歿trade_success_blocks_count[r[0]]}")
+                #     continue
+                # if r[0] in trade_delegate_blocks_count and len(trade_delegate_blocks_count[r[0]]) >= MAX_DELEGATE_COUNT:
+                #     msg_list.append(f"銆恵r[0]}銆戝凡鎸傚崟锛歿trade_delegate_blocks_count[r[0]]}")
+                #     continue
+                if len(r) > 8:
+                    can_buy_blocks.append((r[0], r[6], r[7], r[8]))
+                else:
+                    # 锛堟澘鍧楀悕绉�,韬綅,鏉垮潡娑ㄥ仠鏁伴噺锛�
+                    can_buy_blocks.append((r[0], 0, 1, 1))
+                if r[4]:
+                    can_buy_strong_blocks.append(r[0])
+                if r[3]:
+                    msg_list.append(r[3])
+                if r[5]:
+                    active_buy_blocks.append(r[0])
+                    msg_list.append(f"銆恵r[0]}銆戠Н鏋佷拱鍏�({r[5]})")
+            else:
+                if r[3]:
+                    msg_list.append(r[3])
+        # 鎵�鏈夋澘鍧楅兘鏄嫭鑻�
+        if unique_count == len(blocks_compute_results):
+            return can_buy_blocks, True, ",".join(msg_list), can_buy_strong_blocks, keys, active_buy_blocks
+        return can_buy_blocks, False, ",".join(msg_list), can_buy_strong_blocks, keys, active_buy_blocks
 
     # 鏇存柊浠g爜鏉垮潡鍒ゆ柇鏄惁鍙互涔扮殑缁撴灉
+    # high_level_general_code_blocks 楂樹綅娉涘寲鏉垮潡
     @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)
+                              latest_current_limit_up_records,
+                              before_blocks_dict, current_limit_up_block_codes_dict, delegate_codes, deal_codes):
+        yesterday_current_limit_up_codes = set()
+        yesterday_current_limit_up_records_dict = {}
+        yesterday_current_limit_up_records = latest_current_limit_up_records[0][1]
+        if yesterday_current_limit_up_records:
+            for r in yesterday_current_limit_up_records:
+                yesterday_current_limit_up_codes.add(r[0])
+                yesterday_current_limit_up_records_dict[r[0]] = r
+        high_level_general_code_blocks = {}
+        # 鏄惁鏄�3鏉垮強浠ヤ笂鐨勯珮浣嶆澘
+        for r in current_limit_up_datas:
+            count = kpl_util.get_high_level_count(r[4])
+            if count >= 3 and r[0] in yesterday_current_limit_up_codes:
+                latest_datas = latest_current_limit_up_records[:count - 1]
+                # 鏄珮浣嶆澘
+                # 褰撴棩绮鹃��
+                blocks = set(r[6].split("銆�"))
+                for d in latest_datas:
+                    for dd in d[1]:
+                        if dd[0] == r[0]:
+                            blocks.add(dd[5])
+                            break
+                f_blocks = []
+                for b in blocks:
+                    if b:
+                        f_blocks.append(b)
+                high_level_general_code_blocks[r[0]] = f_blocks
+
+        can_buy_blocks, unique, msg, can_buy_strong_blocks, keys, active_buy_blocks = cls.__compute_can_buy_blocks(code,
+                                                                                                                   current_limit_up_datas,
+                                                                                                                   limit_up_record_datas,
+                                                                                                                   yesterday_current_limit_up_codes,
+                                                                                                                   before_blocks_dict,
+                                                                                                                   current_limit_up_block_codes_dict,
+                                                                                                                   high_level_general_code_blocks,
+                                                                                                                   delegate_codes,
+                                                                                                                   deal_codes)
         # 淇濆瓨鏉垮潡璁$畻缁撴灉
-        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):
-        # 鍔犺浇娑ㄥ仠浠g爜鐨勭洰鏍囨澘鍧�
-        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
+        cls.__can_buy_compute_result_dict[code] = (
+            can_buy_blocks, unique, msg, can_buy_strong_blocks, keys, active_buy_blocks)
 
 
 if __name__ == "__main__":
-    pass
+    KPLPlateForbiddenManager().compute()

--
Gitblit v1.8.0