From 81f328532e366eef171b71810b221a9294dda78f Mon Sep 17 00:00:00 2001
From: Administrator <admin@example.com>
Date: 星期四, 21 十二月 2023 14:31:58 +0800
Subject: [PATCH] 买入条件调整/L撤调整

---
 third_data/code_plate_key_manager.py |  774 +++++++++++++++++++++++++++++++++++++++++++++++++++-------
 1 files changed, 672 insertions(+), 102 deletions(-)

diff --git a/third_data/code_plate_key_manager.py b/third_data/code_plate_key_manager.py
index 4a13787..a109fc0 100644
--- a/third_data/code_plate_key_manager.py
+++ b/third_data/code_plate_key_manager.py
@@ -3,67 +3,168 @@
 """
 
 # 娑ㄥ仠浠g爜鍏抽敭璇嶆澘鍧楃鐞�
+import copy
 import json
+import time
 
 import constant
-import global_data_loader
-import global_util
-import log
-import tool
-from db import redis_manager
+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, async_log_util
+from db import redis_manager_delegate as redis_manager
 
-from log import logger_kpl_limit_up
-from trade import trade_manager
+from log_module.log import logger_kpl_block_can_buy
+from third_data.kpl_util import KPLPlatManager
+from trade import trade_manager, l2_trade_util
 
 
-# 瀹炴椂寮�鐩樺暒甯傚満鏁版嵁
-class RealTimeKplMarketData:
-    # 绮鹃�夊墠5
-    top_5_reason_set = set()
-    # 琛屼笟鍓�5
-    top_5_industry_set = set()
+# 浠g爜绮鹃�夋澘鍧楃鐞�
+class KPLCodeJXBlockManager:
+    __db = 3
+    __redisManager = redis_manager.RedisManager(3)
+    __code_blocks = {}
+    # 澶囩敤
+    __code_by_blocks = {}
 
-    @classmethod
-    def set_top_5_reasons(cls, datas):
-        temp_set = set()
-        base_count = 5
-        for i in range(0, len(datas)):
-            if datas[i][1] in constant.KPL_INVALID_BLOCKS:
-                base_count += 1
-            if i >= base_count:
-                break
-            if datas[i][3] > 5000 * 10000:
-                temp_set.add(datas[i][1])
-        cls.top_5_reason_set = temp_set
+    __instance = None
 
-    @classmethod
-    def set_top_5_industry(cls, datas):
-        temp_set = set()
-        base_count = 5
-        for i in range(0, len(datas)):
-            if datas[i][1] in constant.KPL_INVALID_BLOCKS:
-                base_count += 1
-            if i >= base_count:
-                break
+    def __new__(cls, *args, **kwargs):
+        if not cls.__instance:
+            cls.__instance = super(KPLCodeJXBlockManager, cls).__new__(cls, *args, **kwargs)
+        return cls.__instance
 
-            if datas[i][2] > 5000 * 10000:
-                temp_set.add(datas[i][1])
-        cls.top_5_reason_set = temp_set
+    def __get_redis(self):
+        return self.__redisManager.getRedis()
 
-    # 鑾峰彇鑳藉涔扮殑琛屼笟鍏抽敭瀛梥et
-    @classmethod
-    def get_can_buy_key_set(cls):
-        temp_set = cls.top_5_reason_set | cls.top_5_industry_set
-        return temp_set
-
-    @classmethod
-    def is_in_top(cls, keys):
-        reasons = cls.get_can_buy_key_set()
-        temp_set = keys & reasons
-        if temp_set:
-            return True, temp_set
+    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:
+            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_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:
-            return False, None
+            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 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, 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) / 1.1, 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:
+                        blocks = kpl_api.getCodeBlocks(code)
+                        self.save_jx_blocks(code, blocks, current_limit_up_blocks)
+                        async_log_util.info(logger_kpl_block_can_buy, f"{code}:鑾峰彇鍒扮簿閫夋澘鍧�-{blocks}")
+                    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:
+                                # 璺濈涓婃鏇存柊鏃堕棿杩囧幓浜�5鍒嗛挓
+                                blocks = kpl_api.getCodeBlocks(code)
+                                self.save_jx_blocks(code, blocks, current_limit_up_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.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}")
+        except Exception as e:
+            logger_kpl_block_can_buy.error(f"{code} 鑾峰彇鏉垮潡鍑洪敊")
+            logger_kpl_block_can_buy.exception(e)
+
+
+# 寮�鐩樺暒绂佹浜ゆ槗鏉垮潡绠$悊
+class KPLPlateForbiddenManager:
+    __redisManager = redis_manager.RedisManager(3)
+    __kpl_forbidden_plates_cache = set()
+
+    __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:
@@ -97,23 +198,27 @@
 
     # 浠婃棩娑ㄥ仠鍘熷洜鍙樺寲
     def set_today_limit_up_reason_change(self, code, from_reason, to_reason):
-        self.__get_redis().sadd(f"kpl_limit_up_reason_his-{code}", from_reason)
-        self.__get_redis().expire(f"kpl_limit_up_reason_his-{code}", tool.get_expire())
+        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)
 
+    # 璁剧疆浠g爜鐨勪粖鏃ユ定鍋滃師鍥�
     def __set_total_keys(self, code):
         keys = set()
-        keys_his = self.__get_redis().smembers(f"kpl_limit_up_reason_his-{code}")
-        keys |= keys_his
+        # keys_his = self.__get_redis().smembers(f"kpl_limit_up_reason_his-{code}")
+        # keys |= keys_his
         if code in self.today_limit_up_reason_dict:
-            keys.add(self.today_limit_up_reason_dict.get(code))
+            if self.today_limit_up_reason_dict.get(code) not in constant.KPL_INVALID_BLOCKS:
+                keys.add(self.today_limit_up_reason_dict.get(code))
         self.total_code_keys_dict[code] = keys
         for k in keys:
             if k not in self.total_key_codes_dict:
                 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)
+
+    # 鏍规嵁浼犲叆鐨勫叧閿瘝涓庢定鍋滀唬鐮佷俊鎭尮閰嶈韩浣�
 
     def get_codes_by_key_without_mine(self, key, code):
         # 鍙瘮杈冧粖鏃ユ定鍋滃師鍥�
@@ -123,14 +228,134 @@
         codes_set.discard(code)
         return codes_set
 
+    # 娑ㄥ仠鍘熷洜鍖归厤鍏抽敭瀛�(鍜屾定鍋滃垪琛ㄤ腑鐨勬定鍋滃師鍥犲仛瀵规瘮),杩斿洖:{鍏抽敭璇�:浠g爜闆嗗悎}
+    def match_limit_up_reason_keys(self, code, keys):
+        fresult = {}
+        for k in keys:
+            if k in self.total_key_codes_dict:
+                codes = set(self.total_key_codes_dict[k])
+                codes.discard(code)
+                if codes:
+                    fresult[k] = codes
+        return fresult
 
-# 鐩爣浠g爜鍏抽敭璇嶇鐞�
-class TargetCodePlateKeyManager:
+
+# 瀹炴椂寮�鐩樺暒甯傚満鏁版嵁
+class RealTimeKplMarketData:
+    # 绮鹃�夊墠5
+    top_5_reason_list = []
+    # 琛屼笟鍓�5
+    top_5_industry_list = []
+    #
+    top_5_key_dict = {}
+    total_reason_dict = {}
+    total_industry_dict = {}
+    __KPLPlateForbiddenManager = KPLPlateForbiddenManager()
+    __LimitUpCodesPlateKeyManager = LimitUpCodesPlateKeyManager()
+    __KPLPlatManager = KPLPlatManager()
+
+    @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
+
+        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_top_5_industry(cls, datas):
+        for d in datas:
+            cls.total_industry_dict[d[1]] = d
+        temp_list = []
+        for i in range(0, len(datas)):
+            if datas[i][1] in constant.KPL_INVALID_BLOCKS:
+                continue
+            temp_list.append((datas[i][1], datas[i][2], len(temp_list)))
+            if len(temp_list) > 10:
+                break
+            if datas[i][2] < 3 * 10000 * 10000:
+                break
+        cls.top_5_industry_list = temp_list
+        cls.__reset_top_5_dict()
+
+    @classmethod
+    def __reset_top_5_dict(cls):
+        temp_dict = {}
+        for t in cls.top_5_industry_list:
+            temp_dict[t[0]] = t
+        for t in cls.top_5_reason_list:
+            temp_dict[t[0]] = t
+        cls.top_5_key_dict = temp_dict
+
+    # 鑾峰彇鑳藉涔扮殑琛屼笟鍏抽敭瀛梥et
+    @classmethod
+    def get_can_buy_key_set(cls):
+        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()
+        forbidden_plates = cls.__KPLPlateForbiddenManager.list_all_cache()
+        reasons = reasons - forbidden_plates
+        temp_set = keys & reasons
+        if temp_set:
+            return True, temp_set
+        else:
+            return False, None
+
+
+# 浠g爜鍘嗗彶娑ㄥ仠鍘熷洜涓庢澘鍧楃鐞�
+class CodesHisReasonAndBlocksManager:
     __redisManager = redis_manager.RedisManager(1)
     # 鍘嗗彶娑ㄥ仠鍘熷洜
     __history_limit_up_reason_dict = {}
-    # 浜岀骇琛屼笟
-    __second_industry_dict = {}
     # 鏉垮潡
     __blocks_dict = {}
 
@@ -139,56 +364,90 @@
 
     def set_history_limit_up_reason(self, code, reasons):
         self.__history_limit_up_reason_dict[code] = set(reasons)
-        self.__get_redis().setex(f"kpl_his_limit_up_reason-{code}", tool.get_expire(), json.dumps(list(reasons)))
+        RedisUtils.setex(self.__get_redis(), f"kpl_his_limit_up_reason-{code}", tool.get_expire(),
+                         json.dumps(list(reasons)))
 
     # 濡傛灉杩斿洖鍊间笉涓篘one琛ㄧず宸茬粡鍔犺浇杩囧巻鍙插師鍥犱簡
     def get_history_limit_up_reason(self, code):
         reasons = self.__history_limit_up_reason_dict.get(code)
         if reasons is None:
             # 浠庡唴瀛樹腑鍔犺浇
-            val = self.__get_redis().get(f"kpl_his_limit_up_reason-{code}")
+            val = RedisUtils.get(self.__get_redis(), f"kpl_his_limit_up_reason-{code}")
             if val is not None:
                 val = set(json.loads(val))
                 self.__history_limit_up_reason_dict[code] = val
-            return self.__history_limit_up_reason_dict.get(code)
+            if code in self.__history_limit_up_reason_dict:
+                return self.__history_limit_up_reason_dict.get(code)
+            else:
+                return None
         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)
-        self.__get_redis().setex(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)
         if reasons is None:
             # 浠庡唴瀛樹腑鍔犺浇
-            val = self.__get_redis().get(f"kpl_blocks-{code}")
+            val = RedisUtils.get(self.__get_redis(), f"kpl_blocks-{code}")
             if val is not None:
                 val = set(json.loads(val))
                 self.__blocks_dict[code] = val
-            return self.__blocks_dict.get(code)
+            if code in self.__blocks_dict:
+                return self.__blocks_dict.get(code)
+            else:
+                return None
         else:
             return reasons
 
-    # 杩斿洖key闆嗗悎(鎺掗櫎鏃犳晥鏉垮潡),浠婃棩娑ㄥ仠鍘熷洜,浠婃棩鍘嗗彶娑ㄥ仠鍘熷洜,鍘嗗彶娑ㄥ仠鍘熷洜,浜岀骇,鏉垮潡
+    def get_total_keys(self, code):
+        reasons = self.get_history_limit_up_reason(code)
+        if reasons is None:
+            reasons = set()
+        blocks = self.get_blocks(code)
+        if blocks is None:
+            blocks = set()
+        return reasons | blocks
+
+
+# 鐩爣浠g爜鏉垮潡鍏抽敭璇嶇鐞�
+class TargetCodePlateKeyManager:
+    __redisManager = redis_manager.RedisManager(1)
+    __CodesPlateKeysManager = CodesHisReasonAndBlocksManager()
+    __KPLCodeJXBlockManager = KPLCodeJXBlockManager()
+
+    def __get_redis(self):
+        return self.__redisManager.getRedis()
+
+    # 杩斿洖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 = self.__get_redis().smembers(f"kpl_limit_up_reason_his-{code}")
-        k2 = set()
-        if code in self.__history_limit_up_reason_dict:
-            k2 = self.__history_limit_up_reason_dict[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()
         industry = global_util.code_industry_map.get(code)
         if industry:
             k3 = {industry}
 
         k4 = set()
-        if code in self.__blocks_dict:
-            k4 = self.__blocks_dict[code]
+        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])
         for k in [k1, k11, k2, k3, k4]:
             keys |= k
 
@@ -199,42 +458,353 @@
 
 
 class CodePlateKeyBuyManager:
+    # 鏃犳澘鍧�
+    BLOCK_TYPE_NONE = -1
+    # 涓�鑸澘鍧�
+    BLOCK_TYPE_COMMON = 0
+    # 寮哄娍鏉垮潡
+    BLOCK_TYPE_STRONG = 1
+    # 鐚涙媺鏉垮潡
+    BLOCK_TYPE_SOON_LIMIT_UP = 2
+    # 娼滀紡鏉垮潡
+    BLOCK_TYPE_START_UP = 3
+
     __TargetCodePlateKeyManager = TargetCodePlateKeyManager()
     __LimitUpCodesPlateKeyManager = LimitUpCodesPlateKeyManager()
+    __CodesHisReasonAndBlocksManager = CodesHisReasonAndBlocksManager()
+    __CodesTradeStateManager = trade_manager.CodesTradeStateManager()
+    __can_buy_compute_result_dict = {}
+
+    @classmethod
+    def __remove_from_l2(cls, code, msg):
+        # 鏍规嵁韬綅绉婚櫎浠g爜
+        # return
+        # 涓嬭繃鍗曠殑浠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)
+
+    # 杩斿洖鍐呭(鏄惁鍙拱, 鏄惁涓虹嫭鑻�, 鎻忚堪淇℃伅)
+    @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, 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 not block_codes:
+            # 楂樹綅鏉挎硾鍖栨澘鍧椾腑鏃犳澘鍧�
+            if not high_level_block_codes.get(block):
+                return False, True, f"{block}:鏉垮潡鏃犳定鍋�", 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
+        # 鍙互涔扮殑鏈�澶ф帓鍚�
+        # 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:
+            if d[5] != block:
+                general_blocks = high_level_code_blocks.get(d[0])
+                if not general_blocks or block not in general_blocks:
+                    # 娌″湪娉涘寲鏉垮潡涓�
+                    continue
+            if d[4].find("杩炴澘") > 0:
+                if d[4].replace("杩炴澘", "").isdigit():
+                    count = int(d[4].replace("杩炴澘", ""))
+                    if count >= 3:
+                        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()
+        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_reason_dict,
+                                                                                                yesterday_current_limit_up_codes,
+                                                                                                exclude_first_codes,
+                                                                                                len(
+                                                                                                    current_open_limit_up_codes),
+                                                                                                shsz=True,
+                                                                                                limit_up_time=first_limit_up_time)
+        # 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
+
+        if current_shsz_rank < len(current_open_limit_up_codes) + max_rank:
+            return True, False, f"銆恵block}銆戝墠鎺掍唬鐮侊細{current_shsz_rank}", is_strong_block
+        else:
+            # 鐪嬭嚜鐢辨祦閫氬競鍊兼槸鍚﹀皬浜�20浜�
+            if is_strong_block and current_shsz_rank < len(current_open_limit_up_codes) + max_rank + 1:
+                zyltgb = global_util.zyltgb_map.get(code)
+                if zyltgb and zyltgb < 20 * 100000000:
+                    return True, False, f"銆恵block}銆戝己鍔挎澘鍧� 鑷敱娴侀�氬競鍊�({zyltgb})灏忎簬20浜�", is_strong_block
+            return False, False, f"銆恵block}銆戝墠鎺掍唬鐮侊細{front_current_shsz_rank_codes} 瓒呰繃{len(current_open_limit_up_codes) + max_rank}涓�", is_strong_block
+
+        # 杩囨椂鐨勪唬鐮�
+        # 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}锛�"
+
+    # 鑾峰彇鍙互涔扮殑鏉垮潡
+    # current_limit_up_datas: 浠婃棩瀹炴椂娑ㄥ仠
+    # latest_2_day_limit_up_datas锛氭渶杩�2澶╃殑瀹炴椂娑ㄥ仠锛堜笉鍚粖鏃ワ級
+    # 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, current_limit_up_block_codes_dict, high_level_general_code_blocks,
+                          high_level_general_block_codes):
+        # 鍔犺浇娑ㄥ仠浠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 = []
+
+        # 鑾峰彇鐩爣浠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
+
+        # log.logger_kpl_debug.info("{}鏈�缁堝叧閿瘝锛歿}", code, keys)
+
+        # 娑ㄥ仠鍒楄〃涓尮閰嶅叧閿瘝锛岃繑鍥烇紙鏉垮潡:浠g爜闆嗗悎锛夛紝浠g爜闆嗗悎涓凡缁忔帓闄よ嚜韬�
+
+        fresults = []
+        if not keys:
+            return fresults, set()
+        code_limit_up_reason_dict = {}
+        load_code_block()
+        for block in keys:
+            can_buy, unique, msg, is_strong = 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,
+                                                                     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))
+        return fresults, keys
 
     # 鏄惁鍙互涓嬪崟
+    # 杩斿洖锛氬彲浠ヤ拱鐨勬澘鍧�,鏄惁鐙嫍,娑堟伅
     @classmethod
     def can_buy(cls, code):
-        keys, k1, k11, k2, k3, k4 = cls.__TargetCodePlateKeyManager.get_plate_keys(code)
-        # 鏉垮潡Key鏄惁鍦ㄥ競鍦哄墠5key涓�
-        is_in, valid_keys = RealTimeKplMarketData.is_in_top(keys)
-        if not valid_keys:
-            return False, "鏉垮潡鏈湪甯傚満娴佸叆鍓�5"
-        # 鐩稿悓鏉垮潡涓槸鍚﹀凡缁忔湁鍒殑绁ㄦ定鍋�
-        is_back = False, ''
-        for key in valid_keys:
-            codes = cls.__LimitUpCodesPlateKeyManager.get_codes_by_key_without_mine(key, code)
-            if codes and len(codes) > 0:
-                is_back = True, key
-                break
-        if not is_back[0]:
-            return False, f"鏉垮潡涓涓定鍋滐細{valid_keys}"
-        # 鐪嬫澘鍧椾腑鏄惁宸茬粡鏈夊凡缁忎笅鍗曠殑鎴栬�呮垚浜ょ殑浠g爜
-        codes = trade_manager.get_codes_by_trade_states(
-            {trade_manager.TRADE_STATE_BUY_DELEGATED, trade_manager.TRADE_STATE_BUY_PLACE_ORDER,
-             trade_manager.TRADE_STATE_BUY_SUCCESS})
-        # 閬嶅巻宸茬粡鎴愪氦/涓嬪崟鐨勪唬鐮侊紝鑾峰彇鍏舵定鍋滃師鍥狅紝鐒跺悗鍜屽綋鍓嶄唬鐮佹定鍋滃師鍥犲仛姣旇緝锛屾湁鐩稿悓浠g爜鐨勪笉鑳戒拱
+        if constant.TEST:
+            return ["娴嬭瘯"], 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,
+                                 current_limit_up_block_codes_dict, high_level_general_code_blocks):
+        # 鏍规嵁浠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_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}))
+        codes = codes_delegate | codes_success
+        # 缁熻鎴愪氦浠g爜鐨勬澘鍧�
+        trade_codes_blocks_dict = {}
+        # 宸茬粡鎴愪氦鐨勬澘鍧�
+        trade_success_blocks_count = {}
+        trade_delegate_blocks_count = {}
         for c in codes:
             keys_, k1_, k11_, k2_, k3_, k4_ = cls.__TargetCodePlateKeyManager.get_plate_keys(c)
-            # 瀹炴椂娑ㄥ仠鍘熷洜
-            for k_ in k1_:
-                # 褰撳墠浠g爜宸茬粡鏈夋寕鐨勬垨鑰呮垚浜ょ殑
-                if k_ in valid_keys:
-                    return False, f"{k_}鏉垮潡涓殑{c}宸茬粡涓嬪崟/涔板叆鎴愬姛锛屽悓涓�鏉垮潡涓彧鑳戒拱1涓エ"
-        return True, f"娑ㄥ仠鍘熷洜锛歿is_back[1]}"
+            # 瀹炴椂娑ㄥ仠鍘熷洜 + 鎺ㄨ崘鍘熷洜
+            if not k1_:
+                trade_codes_blocks_dict[c] = k4_
+            else:
+                trade_codes_blocks_dict[c] = k1_
+        # 缁熻鏉垮潡涓殑浠g爜
+        trade_block_codes_dict = {}
+        for c in trade_codes_blocks_dict:
+            for b in trade_codes_blocks_dict[c]:
+                if c in codes_success:
+                    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-------------
+
+        #
+        can_buy_blocks = []
+        can_buy_strong_blocks = []
+        unique_count = 0
+        msg_list = []
+
+        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
+                can_buy_blocks.append(r[0])
+                if r[4]:
+                    can_buy_strong_blocks.append(r[0])
+                if r[3]:
+                    msg_list.append(r[3])
+            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
+        return can_buy_blocks, False, ",".join(msg_list), can_buy_strong_blocks, keys
+
+    # 鏇存柊浠g爜鏉垮潡鍒ゆ柇鏄惁鍙互涔扮殑缁撴灉
+    # high_level_general_code_blocks 楂樹綅娉涘寲鏉垮潡
+    @classmethod
+    def update_can_buy_blocks(cls, code, current_limit_up_datas, limit_up_record_datas,
+                              latest_current_limit_up_records,
+                              before_blocks_dict, current_limit_up_block_codes_dict):
+        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:
+            if r[4].find("杩炴澘") > 0:
+                if r[4].replace("杩炴澘", "").isdigit():
+                    count = int(r[4].replace("杩炴澘", ""))
+                    if count >= 3:
+                        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 = 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)
+        # 淇濆瓨鏉垮潡璁$畻缁撴灉
+        cls.__can_buy_compute_result_dict[code] = (can_buy_blocks, unique, msg, can_buy_strong_blocks, keys)
 
 
 if __name__ == "__main__":
-    datas = log.load_kpl_reason_changes()
-    for k in datas:
-        LimitUpCodesPlateKeyManager().set_today_limit_up_reason_change(k[0], k[1], k[2])
+    pass

--
Gitblit v1.8.0