Administrator
2023-07-19 3e96eb6ec6e8c71ffdabe9f76ad1a3db301e749e
third_data/code_plate_key_manager.py
@@ -6,11 +6,12 @@
import json
import constant
from third_data import kpl_block_util
from utils import global_util, tool
from logs_ import log
from log_module import log
from db import redis_manager
from logs_.log import logger_kpl_limit_up, logger_kpl_block_can_buy
from log_module.log import logger_kpl_limit_up, logger_kpl_block_can_buy
from third_data.kpl_util import KPLPlatManager
from trade import trade_manager
@@ -124,9 +125,9 @@
                # (名称,净流入金额,排名)
                temp_list.append((datas[i][1], datas[i][3], len(temp_list)))
                # 只获取前10个
                if len(temp_list) > 5:
                if len(temp_list) > 10:
                    break
                if datas[i][3] < 1 * 10000 * 10000:
                if datas[i][3] < 3 * 10000 * 10000:
                    break
        for temp in temp_list:
@@ -147,9 +148,9 @@
            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) > 5:
            if len(temp_list) > 10:
                break
            if datas[i][2] < 1 * 10000 * 10000:
            if datas[i][2] < 3 * 10000 * 10000:
                break
        cls.top_5_industry_list = temp_list
        cls.__reset_top_5_dict()
@@ -212,7 +213,7 @@
            return False, None
#
# 代码历史涨停原因与板块管理
class CodesHisReasonAndBlocksManager:
    __redisManager = redis_manager.RedisManager(1)
    # 历史涨停原因
@@ -273,7 +274,7 @@
        return reasons | blocks
# 目标代码关键词管理
# 目标代码板块关键词管理
class TargetCodePlateKeyManager:
    __redisManager = redis_manager.RedisManager(1)
    __CodesPlateKeysManager = CodesHisReasonAndBlocksManager()
@@ -287,7 +288,7 @@
        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 = self.__CodesPlateKeysManager.get_history_limit_up_reason(code)
        if k2 is None:
@@ -310,22 +311,155 @@
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()
    # 是否可以下单
    # 获取可以买的板块
    # current_limit_up_datas: 今日实时涨停
    # latest_2_day_limit_up_datas:最近2天的实时涨停(不含今日)
    # limit_up_record_datas:今日历史涨停
    @classmethod
    def can_buy(cls, code):
        if constant.TEST:
            return True, ""
    def get_can_buy_block(cls, code, current_limit_up_datas, latest_2_day_limit_up_datas, limit_up_record_datas):
        now_time = int(tool.get_now_time_str().replace(":", ""))
        times = [100000, 103000, 110000, 133000, 150000]
        time_index = 0
        for i in range(len(times)):
            if now_time < times[i]:
                time_index = i
                break
        # 获取板块
        keys, k1, k11, k2, k3, k4 = cls.__TargetCodePlateKeyManager.get_plate_keys(code)
        log.logger_kpl_debug.info("{}关键词:{},{},{},{},{},{}", code, keys, k1, k11, k2, k3, k4)
        # 涨停列表中匹配关键词
        log.logger_kpl_debug.info("{}关键词:所有-{},今日-{},今日历史-{},历史-{},二级行业-{},代码板块-{}", code, keys, k1, k11, k2, k3, k4)
        # 涨停列表中匹配关键词,返回(板块:代码集合),代码集合中已经排除自身
        match_limit_up_result = cls.__LimitUpCodesPlateKeyManager.match_limit_up_reason_keys(code, keys)
        log.logger_kpl_debug.info("{}关键词身位匹配结果:{}", code, match_limit_up_result)
        if not match_limit_up_result:
            return False, "未在涨停列表中未匹配到涨停原因"
            return cls.BLOCK_TYPE_NONE, None, "未在涨停列表中未匹配到涨停原因"
        # 获取板块归类
        for block in match_limit_up_result:
            # 获取强势板块
            strong_result = kpl_block_util.is_strong_block(block, current_limit_up_datas, latest_2_day_limit_up_datas)
            # 获取猛拉板块
            soon_limit_up_result = kpl_block_util.is_soon_limit_up(code, block, limit_up_record_datas)
            # 获取身位
            rank = kpl_block_util.get_code_rank(code, block, limit_up_record_datas)
            # 主板身位
            sh_sz_rank = kpl_block_util.get_sh_sz_code_rank(code, block, limit_up_record_datas)
            # 是否后排
            is_back_row = kpl_block_util.is_back_row(code, block, current_limit_up_datas)
            # 是否满足市场流入前几
            is_in_top_input = RealTimeKplMarketData.is_in_top(set([block]))[0]
            log.logger_kpl_debug.info("{}-{}  板块判断结果:强势板块-{}  猛拉板块-{} 身位-{} 主板身位-{} 是否后排-{} 是否在流入前排-{}", code, block,
                                      strong_result, soon_limit_up_result, rank, sh_sz_rank, is_back_row,
                                      is_in_top_input)
            if time_index == 0:
                # 09:30:00 - 10:00:00
                if strong_result[0]:
                    # 强势板块
                    # 买主板龙1,2,3,4  买后排
                    if is_back_row and sh_sz_rank <= 3:
                        return cls.BLOCK_TYPE_STRONG, block, f"{block} 强势板块:买主板龙1,2,3,4  买后排"
                if soon_limit_up_result[0]:
                    # 猛拉板块
                    # 只买龙2 买后排
                    if is_back_row and rank == 1:
                        return cls.BLOCK_TYPE_SOON_LIMIT_UP, block, f"{block} 猛拉板块:只买龙2,买后排"
                # 其他板块
                if is_in_top_input and sh_sz_rank <= 1 and is_back_row:
                    # 看精选/行业流入   买龙主板1,2  买后排
                    return cls.BLOCK_TYPE_COMMON, block, f"{block} 其他板块:看精选/行业流入   买龙主板1,2  买后排"
            elif time_index == 1:
                # 10:00:00 - 10:30:00
                if strong_result[0]:
                    # 强势板块
                    # 买主板龙1,2,3  买后排
                    if is_back_row and sh_sz_rank <= 2:
                        return cls.BLOCK_TYPE_STRONG, block, f"{block} 强势板块:买主板龙1,2,3  买后排"
                if soon_limit_up_result[0]:
                    # 猛拉板块
                    # 只买龙2 买后排
                    if is_back_row and rank == 1:
                        return cls.BLOCK_TYPE_SOON_LIMIT_UP, block, f"{block} 猛拉板块:只买龙2,买后排"
                # 其他板块
                if is_in_top_input and sh_sz_rank <= 1 and is_back_row:
                    # 看精选/行业流入   买龙主板1,2  买后排
                    return cls.BLOCK_TYPE_COMMON, block, f"{block} 其他板块:看精选/行业流入   买龙主板1,2  买后排"
            elif time_index == 2:
                # 10:30:00 - 11:00:00
                if strong_result[0]:
                    # 强势板块
                    # 买主板龙1,2  买后排
                    if is_back_row and sh_sz_rank <= 1:
                        return cls.BLOCK_TYPE_STRONG, block, f"{block} 强势板块:买主板龙1,2  买后排"
                if soon_limit_up_result[0]:
                    # 猛拉板块
                    # 只买龙2 买后排
                    if is_back_row and rank == 1:
                        return cls.BLOCK_TYPE_SOON_LIMIT_UP, block, f"{block} 猛拉板块:只买龙2,买后排"
                # 其他板块
                if is_in_top_input and sh_sz_rank <= 1 and is_back_row:
                    # 看精选/行业流入   买龙主板1,2  买后排
                    return cls.BLOCK_TYPE_COMMON, block, f"{block} 其他板块:看精选/行业流入   买龙主板1,2  买后排"
            elif time_index == 3:
                # 11:00:00 - 13:30:00
                if soon_limit_up_result[0]:
                    # 猛拉板块
                    # 只买龙2 买后排
                    if is_back_row and rank == 1:
                        return cls.BLOCK_TYPE_SOON_LIMIT_UP, block, f"{block} 猛拉板块:只买龙2,买后排"
                # 其他板块
                if is_in_top_input and sh_sz_rank <= 1 and is_back_row:
                    # 看精选/行业流入   买龙主板1,2  买后排
                    return cls.BLOCK_TYPE_COMMON, block, f"{block} 其他板块:看精选/行业流入,买龙主板1,2 ,买后排"
            elif time_index == 4:
                # 13:30:00 - 15:00:00
                if soon_limit_up_result[0]:
                    # 猛拉板块
                    # 只买龙2 买后排
                    if is_back_row and rank == 1:
                        return cls.BLOCK_TYPE_SOON_LIMIT_UP, block, f"{block} 猛拉板块:只买龙2,买后排"
                # 其他板块
                if is_in_top_input:
                    # 精选/行业流入符合
                    if sh_sz_rank <= 1 and is_back_row:
                        # 看精选/行业流入   买龙主板1,2  买后排
                        return cls.BLOCK_TYPE_COMMON, block, f"{block} 其他板块:精选/行业流入符合,买龙主板1,2,买后排"
                else:
                    if sh_sz_rank == 0 and not is_back_row:
                        return cls.BLOCK_TYPE_START_UP, block, f"{block} 其他板块: 买主板龙1,买主板独苗"
        return cls.BLOCK_TYPE_NONE, None, f"板块({match_limit_up_result.keys()})不符合买入条件"
    # 是否可以下单
    # 返回:是否可以下单,消息,板块类型
    @classmethod
    def can_buy(cls, code, current_limit_up_datas, latest_2_day_limit_up_datas, limit_up_record_datas):
        if constant.TEST:
            return True, "", cls.BLOCK_TYPE_NONE
        block_type, block, block_msg = cls.get_can_buy_block(code, current_limit_up_datas, latest_2_day_limit_up_datas,
                                                             limit_up_record_datas)
        if block_type == cls.BLOCK_TYPE_NONE:
            return False, block_msg, block_type
        # ---------------------------------判断目标代码的板块-------------------start------------
        # 判断匹配出的涨停原因,判断是否有已经下单的票
@@ -358,22 +492,22 @@
        # ---------------------------------判断目标代码的板块-------------------end------------
        # 获取板块可以下单的个数
        can_buy_codes_count_dict = {}
        # can_buy_codes_count_dict = {}
        #
        # for key__ in match_limit_up_result:
        #     can_buy_count, msg = RealTimeKplMarketData.get_can_buy_codes_count(code, key__)
        #     can_buy_codes_count_dict[key__] = can_buy_count
        for key__ in match_limit_up_result:
            can_buy_count, msg = RealTimeKplMarketData.get_can_buy_codes_count(code, key__)
            can_buy_codes_count_dict[key__] = can_buy_count
        has_available_key = False
        for key in can_buy_codes_count_dict:
            if can_buy_codes_count_dict[key] > 0:
                has_available_key = True
                break
        if not has_available_key:
            return False, f"匹配到的【{','.join(match_limit_up_result.keys())}】没在精选/行业可以买入的板块中"
        # has_available_key = False
        # for key in can_buy_codes_count_dict:
        #     if can_buy_codes_count_dict[key] > 0:
        #         has_available_key = True
        #         break
        # if not has_available_key:
        #     return False, f"匹配到的【{','.join(match_limit_up_result.keys())}】没在精选/行业可以买入的板块中"
        # ---------------------------------加载已经下单/成交的代码信息------------start-------------
        match_reasons = match_limit_up_result.keys()
        # match_reasons = match_limit_up_result.keys()
        # 判断匹配到的原因是否已经有下单/买入成功的代码
        codes_delegate = set(trade_manager.get_codes_by_trade_states(
            {trade_manager.TRADE_STATE_BUY_DELEGATED, trade_manager.TRADE_STATE_BUY_PLACE_ORDER}))
@@ -385,7 +519,7 @@
        # 统计成交代码的板块
        trade_codes_blocks_dict = {}
        # 已经成交的板块
        trade_success_blocks = set()
        trade_success_blocks_count = {}
        for c in codes:
            keys_, k1_, k11_, k2_, k3_, k4_ = cls.__TargetCodePlateKeyManager.get_plate_keys(c)
            # 实时涨停原因
@@ -395,7 +529,9 @@
        for c in trade_codes_blocks_dict:
            for b in trade_codes_blocks_dict[c]:
                if c in codes_success:
                    trade_success_blocks.add(b)
                    if b not in trade_success_blocks_count:
                        trade_success_blocks_count[b] = set()
                    trade_success_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)
@@ -403,27 +539,32 @@
        # ---------------------------------加载已经下单/成交的代码信息------------end-------------
        msg_list = []
        for key in can_buy_codes_count_dict:
            log.logger_kpl_debug.debug(f"{code}:板块可以下单的数量【{key}】-{can_buy_codes_count_dict[key]}")
            if can_buy_codes_count_dict[key] < 1:
                continue
        for key in [block]:
            # 板块中已经有成交的就不下单了
            if key in trade_success_blocks:
                msg_list.append(f"【{key}】中已经有成交代码")
                log.logger_kpl_debug.debug(f"{code}:板块已经有成交【{key}】")
                continue
            if key in trade_success_blocks_count:
                success_codes_count = len(trade_success_blocks_count[key])
                if success_codes_count >= 2:
                    msg_list.append(f"【{key}】中已经有{success_codes_count}个成交代码")
                    log.logger_kpl_debug.debug(f"{code}:板块({key})已经有成交【{trade_success_blocks_count[key]}】")
                    continue
                # 10:30以后买1个
                if int(tool.get_now_time_str().replace(":", "")) > int("103000") and success_codes_count >= 1:
                    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, block_type
            # 板块可以下单数量
            if trade_block_codes_dict.get(key) is None or len(trade_block_codes_dict.get(key)) < \
                    can_buy_codes_count_dict[key]:
                order_count = len(trade_block_codes_dict.get(key)) if key in trade_block_codes_dict else 0
                logger_kpl_block_can_buy.info(
                    f"code={code}:【{key}】可以下单,现有数量:{order_count} 最大数量:{can_buy_codes_count_dict[key]}")
                return True, f"可以下单,板块:【{key}】,板块中已经下单的数量:{order_count}"
            else:
                order_count = len(trade_block_codes_dict.get(key))
                msg_list.append(f"【{key}】中下单代码数量{order_count}/允许下单数量{can_buy_codes_count_dict[key]}")
            # if trade_block_codes_dict.get(key) is None or len(trade_block_codes_dict.get(key)) < \
            #         can_buy_codes_count_dict[key]:
            #     order_count = len(trade_block_codes_dict.get(key)) if key in trade_block_codes_dict else 0
            #     logger_kpl_block_can_buy.info(
            #         f"code={code}:【{key}】可以下单,现有数量:{order_count} 最大数量:{can_buy_codes_count_dict[key]}")
            #     return True, f"可以下单,板块:【{key}】,板块中已经下单的数量:{order_count}"
            # else:
            #     order_count = len(trade_block_codes_dict.get(key))
            #     msg_list.append(f"【{key}】中下单代码数量{order_count}/允许下单数量{can_buy_codes_count_dict[key]}")
        return False, ",".join(msg_list)
        return False, ",".join(msg_list), block_type
if __name__ == "__main__":