Administrator
2024-07-31 75304450cd47c427ade3ad40a7556fc8328a3f29
third_data/code_plate_key_manager.py
@@ -10,15 +10,17 @@
import constant
from code_attribute import code_nature_analyse
from db.redis_manager_delegate import RedisUtils
from third_data import kpl_block_util, kpl_api, kpl_util
from trade.trade_manager import MarketSituationManager
from utils import global_util, tool, buy_condition_util
from third_data import kpl_block_util, kpl_api, kpl_util, kpl_limit_up_data_manager
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 utils import global_util, tool, buy_condition_util, init_data_util
from log_module import log, async_log_util
from db import redis_manager_delegate as redis_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
from trade import trade_manager, l2_trade_util, trade_constant
# 代码精选板块管理
@@ -93,7 +95,7 @@
            # 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)
                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:
@@ -137,6 +139,48 @@
        except Exception as e:
            logger_kpl_block_can_buy.error(f"{code} 获取板块出错")
            logger_kpl_block_can_buy.exception(e)
# 禁止下单的板块
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
# 开盘啦禁止交易板块管理
@@ -505,7 +549,7 @@
        # 根据身位移除代码
        # return
        # 下过单的代码不移除
        if trade_manager.CodesTradeStateManager().get_trade_state_cache(code) != trade_manager.TRADE_STATE_NOT_TRADE:
        if trade_manager.CodesTradeStateManager().get_trade_state_cache(code) != trade_constant.TRADE_STATE_NOT_TRADE:
            # 只要下过单的就不移除
            return
        l2_trade_util.forbidden_trade(code, msg=msg)
@@ -699,7 +743,7 @@
        block_codes_records = set()
        if limit_up_record_datas:
            for k in limit_up_record_datas:
                if code_limit_up_reasons_dict.get(k[3]) == block:
                if block in code_limit_up_reasons_dict.get(k[3]):
                    block_codes_records.add(k[3])
        if not block_codes:
@@ -718,7 +762,7 @@
        is_strong_block = False
        # 最多买老几
        RANKS = [5, 4, 3, 3, 3, 2, 2]
        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
@@ -758,10 +802,12 @@
        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, False, f"【{block}】前排代码:{current_shsz_rank}", is_strong_block, is_active_buy, current_shsz_rank, len(
                block_codes),len(block_codes_records)
            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, False, 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(
            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)
    # 获取可以买的板块
@@ -814,7 +860,8 @@
                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))
            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
    # 是否可以下单
@@ -823,7 +870,7 @@
    @classmethod
    def can_buy(cls, code):
        if constant.TEST:
            return [("测试", 0, 1)], True, cls.BLOCK_TYPE_NONE, [], set(), ["化工"]
            return [("测试", 0, 1, 1)], True, cls.BLOCK_TYPE_NONE, [], set(), ["化工"]
        # if True:
        #     # 测试
        #     return True, "不判断板块身位"
@@ -850,9 +897,9 @@
        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}))
            {trade_constant.TRADE_STATE_BUY_DELEGATED, trade_constant.TRADE_STATE_BUY_PLACE_ORDER}))
        codes_success = set(cls.__CodesTradeStateManager.get_codes_by_trade_states_cache(
            {trade_manager.TRADE_STATE_BUY_SUCCESS}))
            {trade_constant.TRADE_STATE_BUY_SUCCESS}))
        codes = codes_delegate | codes_success
        # 统计成交代码的板块
        trade_codes_blocks_dict = {}
@@ -971,5 +1018,206 @@
            can_buy_blocks, unique, msg, can_buy_strong_blocks, keys, active_buy_blocks)
class LatestLimitUpBlockManager:
    """
    最近涨停的板块管理
    """
    # 看最近7天
    __LATEST_DAY_COUNT = 7
    __days = []
    # 目前涨停
    __current_limit_up_day_datas = {}
    # 曾涨停
    __history_limit_up_day_datas = {}
    # K线数据
    __k_datas = {}
    # 代码的最高涨幅
    __k_max_rate = {}
    __code_name_dict = {}
    # 统计板块数据:{"day":{"板块":[(涨停数,破板数, 代码集合)]}}
    __block_day_datas = {}
    __instance = None
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(LatestLimitUpBlockManager, cls).__new__(cls, *args, **kwargs)
            cls.__load_datas()
        return cls.__instance
    @classmethod
    def __load_datas(cls):
        # 加载最近7天的数据
        __days = HistoryKDatasUtils.get_latest_trading_date_cache(cls.__LATEST_DAY_COUNT - 1)
        now_day = tool.get_now_date_str()
        if __days[0] != now_day:
            __days.insert(0, now_day)
        cls.__days = __days
        # 加载之前6天的涨停,曾涨停,曾涨停代码的最近6天的K线
        for day in __days:
            if day == now_day:
                continue
            limit_up_records = kpl_limit_up_data_manager.get_history_limit_up_datas(day)
            cls.__history_limit_up_day_datas[day] = limit_up_records
            current_limit_up_datas = kpl_limit_up_data_manager.get_current_limit_up_datas(day)
            cls.__current_limit_up_day_datas[day] = current_limit_up_datas
        # 获取代码的k线
        __total_codes = set()
        for d in cls.__current_limit_up_day_datas:
            __total_codes |= set([dd[3] for dd in cls.__history_limit_up_day_datas[d]])
        # 获取最近7天的k线情况
        for code in __total_codes:
            cls.__get_bars(code)
        # 统计前6天的板块信息
        for day in __days:
            if day == now_day:
                continue
            cls.__block_day_datas[day] = cls.__statistics_limit_up_block_infos_by_day(day)
    def set_current_limit_up_data(self, day, datas):
        self.__current_limit_up_day_datas[day] = datas
        self.__history_limit_up_day_datas[day] = kpl_limit_up_data_manager.get_today_history_limit_up_datas_cache()
        # 加载代码K线数据
        __total_codes = set([d[0] for d in datas])
        __total_codes |= set([d[3] for d in self.__history_limit_up_day_datas[day]])
        for code in __total_codes:
            self.__get_bars(code)
    @classmethod
    def __statistics_limit_up_block_infos_by_day(cls, day):
        """
        统计涨停代码信息
        @return:
        """
        # 统计板块的
        current_code_dict = {d[0]: d for d in cls.__current_limit_up_day_datas[day]}
        # history_code_dict = {d[3]: d for d in self.__history_limit_up_day_datas[day]}
        block_codes_dict = {}
        for h in cls.__history_limit_up_day_datas[day]:
            cls.__code_name_dict[h[3]] = h[4]
            if h[2] not in block_codes_dict:
                block_codes_dict[h[2]] = set()
            block_codes_dict[h[2]].add(h[3])
        fdata = {}
        for b in block_codes_dict:
            limit_up_count = 0
            open_limit_up_count = 0
            for code in block_codes_dict[b]:
                if code in current_code_dict:
                    limit_up_count += 1
                else:
                    open_limit_up_count += 1
            fdata[b] = (limit_up_count, open_limit_up_count, block_codes_dict[b])
        return fdata
    def statistics_limit_up_block_infos(self):
        """
        统计涨停板块数据
        @return:
        """
        # 只统计今天的数据
        now_day = tool.get_now_date_str()
        block_dict = self.__statistics_limit_up_block_infos_by_day(now_day)
        self.__block_day_datas[now_day] = block_dict
        # 板块出现的天数
        block_count_dict = {}
        # 板块出现的代码
        block_codes_dict = {}
        for day in self.__block_day_datas:
            for b in self.__block_day_datas[day]:
                if b not in block_count_dict:
                    block_count_dict[b] = set()
                if b not in block_codes_dict:
                    block_codes_dict[b] = set()
                block_count_dict[b].add(day)
                block_codes_dict[b] |= self.__block_day_datas[day][b][2]
        block_count_list = [(k, block_count_dict[k]) for k in block_count_dict]
        block_count_list.sort(key=lambda x: x[1], reverse=True)
        block_count_list = block_count_list[:20]
        # [(涨停原因,累计涨停次数,连续次数)]
        fdatas = []
        today_records_code_dict = {d[3]: d for d in self.__history_limit_up_day_datas.get(now_day)}
        for d in block_count_list:
            b = d[0]
            fdata = [d[0], len(d[1])]
            temp = []
            max_continue_count = 0
            for day in self.__days:
                if d[0] in self.__block_day_datas[day]:
                    temp.append(day)
                else:
                    c = len(temp)
                    if c > max_continue_count:
                        max_continue_count = c
                    temp.clear()
            c = len(temp)
            if c > max_continue_count:
                max_continue_count = c
            temp.clear()
            # 最大连续次数
            fdata.append(max_continue_count)
            # 最高板
            max_rate_info = None
            for code in block_codes_dict[d[0]]:
                if max_rate_info is None:
                    max_rate_info = (code, self.__k_max_rate.get(code),  self.__code_name_dict.get(code))
                if max_rate_info[1] < self.__k_max_rate.get(code):
                    max_rate_info = (code, self.__k_max_rate.get(code), self.__code_name_dict.get(code))
            fdata.append(max_rate_info)
            # 统计今天这个板块中大于二板的代码数量
            limit_up_counts = 0
            for code in block_codes_dict[d[0]]:
                if code in today_records_code_dict and today_records_code_dict[code][12] != '首板':
                    limit_up_counts += 1
            fdata.append(limit_up_counts)
            # 获取每天的数量
            days_datas = []
            for day in self.__days:
                binfo = self.__block_day_datas[day].get(b)
                if not binfo:
                    days_datas.append((0, 0))
                else:
                    days_datas.append((binfo[0], binfo[1]))
            fdata.append(days_datas)
            fdatas.append(fdata)
        return fdatas
    @classmethod
    def __get_bars(cls, code):
        """
        获取K线
        @param code:
        @return:
        """
        if code in cls.__k_datas:
            return cls.__k_datas[code]
        volumes_data = None
        if cls.__days:
            volumes_data = HistoryKDataManager().get_history_bars(code, cls.__days[1])
            if volumes_data:
                volumes_data = volumes_data[:cls.__LATEST_DAY_COUNT - 1]
                cls.__k_datas[code] = volumes_data
        if not volumes_data:
            volumes_data = init_data_util.get_volumns_by_code(code, cls.__LATEST_DAY_COUNT - 1)
            if volumes_data:
                cls.__k_datas[code] = volumes_data
        # 获取最大涨幅
        min_price = volumes_data[-1]["low"]
        for d in volumes_data:
            if min_price > d["low"]:
                min_price = d["low"]
        rate = int((volumes_data[0]["close"] - min_price) * 100 / min_price)
        cls.__k_max_rate[code] = rate
        return cls.__k_datas.get(code)
if __name__ == "__main__":
    pass