Administrator
2023-10-10 21b84025d0d2543b5f6dc8c22859d25ce0e5de30
交易日志格式化处理
9个文件已修改
1个文件已添加
453 ■■■■ 已修改文件
l2/cancel_buy_strategy.py 21 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
l2/l2_data_manager_new.py 61 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
l2/l2_log.py 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
log_module/log_export.py 131 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
output/code_info_output.py 78 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
third_data/code_plate_key_manager.py 12 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
trade/huaxin/huaxin_trade_order_processor.py 9 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
trade/l2_trade_util.py 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
trade/trade_manager.py 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
trade/trade_record_log_util.py 135 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
l2/cancel_buy_strategy.py
@@ -16,7 +16,7 @@
from db.redis_manager_delegate import RedisUtils
from utils import tool
from l2.transaction_progress import TradeBuyQueue
from trade import trade_queue_manager, l2_trade_factor
from trade import trade_queue_manager, l2_trade_factor, trade_record_log_util
from l2 import l2_log, l2_data_source_util
from l2.l2_data_util import L2DataUtil, local_today_num_operate_map, local_today_datas, local_today_buyno_map, \
    local_today_canceled_buyno_map
@@ -347,13 +347,6 @@
                        if need_cancel:
                            rate__ = round(cancel_num / max(buy_num, 1), 2)
                            if rate__ > cancel_rate_threshold:
                                l2_log.trade_record(code, "S撤范围",
                                                    "'start_index':{} , 'end_index':{} ,'range_seconds':{}",
                                                    buy_single_index,
                                                    i,
                                                    range_seconds)
                                l2_log.trade_record(code, "S撤", "'index':{} , 'rate':{} , 'target_rate':{}", i, rate__,
                                                    cancel_rate_threshold)
                                return True, total_data[i]
            finally:
@@ -414,6 +407,9 @@
    # 保存成交位置到执行位置的揽括范围数据
    def __save_watch_index_set(self, code, indexes):
        trade_record_log_util.add_cancel_watch_indexes_log(code,
                                                           CancelWatchIndexesInfo(CancelWatchIndexesInfo.CANCEL_TYPE_H,
                                                                                  list(indexes)))
        CodeDataCacheUtil.set_cache(self.__cancel_watch_indexs_cache, code, indexes)
        key = f"h_cancel_watch_indexs-{code}"
        RedisUtils.setex_async(self.__db, key, tool.get_expire(),
@@ -495,6 +491,7 @@
                        break
            if watch_indexes:
                self.__save_watch_index_set(code, watch_indexes)
                l2_log.h_cancel_debug(code, f"设置监听范围, 数据范围:{real_place_order_index}-{end_index} 监听范围-{watch_indexes}")
                break
@@ -755,6 +752,9 @@
    def __add_watch_indexes(self, code, indexes):
        if not indexes:
            return
        trade_record_log_util.add_cancel_watch_indexes_log(code,
                                                           trade_record_log_util.CancelWatchIndexesInfo(trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_L_DOWN,
                                                                                  list(indexes)))
        if code not in self.__cancel_watch_index_cache:
            self.__cancel_watch_index_cache[code] = set()
        for index in indexes:
@@ -786,6 +786,11 @@
        return set()
    def __set_near_by_trade_progress_indexes(self, code, indexes):
        if indexes:
            trade_record_log_util.add_cancel_watch_indexes_log(code,
                                                               trade_record_log_util.CancelWatchIndexesInfo(
                                                                   trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_L_UP,
                                                                   list(indexes)))
        self.__near_by_trade_progress_index_cache[code] = indexes
        RedisUtils.setex_async(self.__db, f"l_cancel_near_by_index-{code}", tool.get_expire(),
                               json.dumps(list(indexes)))
l2/l2_data_manager_new.py
@@ -13,9 +13,9 @@
from utils import global_util, ths_industry_util, tool
import l2_data_util
from db import redis_manager_delegate as redis_manager
from third_data.code_plate_key_manager import CodePlateKeyBuyManager
from third_data.code_plate_key_manager import CodePlateKeyBuyManager, KPLCodeJXBlockManager
from trade import trade_manager, trade_queue_manager, l2_trade_factor, l2_trade_util, \
    trade_result_manager, current_price_process_manager, trade_data_manager, trade_huaxin
    trade_result_manager, current_price_process_manager, trade_data_manager, trade_huaxin, trade_record_log_util
from l2 import safe_count_manager, l2_data_manager, l2_log, l2_data_source_util, code_price_manager, \
    transaction_progress, cancel_buy_strategy, l2_data_log
from l2.cancel_buy_strategy import SecondCancelBigNumComputer, HourCancelBigNumComputer, DCancelBigNumComputer, \
@@ -214,6 +214,7 @@
    __TradeBuyQueue = transaction_progress.TradeBuyQueue()
    __latest_process_order_unique_keys = {}
    __latest_process_not_order_unique_keys_count = {}
    __trade_log_placr_order_info_dict = {}  # 下单信息保存
    # 初始化
    __TradePointManager = l2_data_manager.TradePointManager()
    __SecondCancelBigNumComputer = SecondCancelBigNumComputer()
@@ -287,6 +288,7 @@
    @classmethod
    def set_real_place_order_index(cls, code, index, buy_single_index):
        trade_record_log_util.add_real_place_order_position_log(code, index, buy_single_index)
        cancel_buy_strategy.set_real_place_position(code, index, buy_single_index)
    # 处理华鑫L2数据
@@ -324,6 +326,8 @@
    def process_add_datas(cls, code, add_datas, capture_timestamp, __start_time):
        now_time_str = tool.get_now_time_str()
        if len(add_datas) > 0:
            if code not in cls.__trade_log_placr_order_info_dict:
                cls.__trade_log_placr_order_info_dict[code] = trade_record_log_util.PlaceOrderInfo()
            # 拼接数据
            local_today_datas[code].extend(add_datas)
            l2.l2_data_util.load_num_operate_map(local_today_num_operate_map, code, add_datas)
@@ -541,6 +545,7 @@
            code)
        if not can:
            l2_log.debug(code, "不可以下单,原因:{}", reason)
            trade_record_log_util.add_cant_place_order_log(code, reason)
            if need_clear_data:
                trade_result_manager.real_cancel_success(code, buy_single_index, buy_exec_index,
                                                         local_today_datas.get(code))
@@ -559,10 +564,25 @@
                l2_log.debug(code, "处理买入成功")
                params_desc = cls.__l2PlaceOrderParamsManagerDict[code].get_buy_rank_desc()
                l2_log.debug(code, params_desc)
                l2_log.trade_record(code, "下单",
                                    "'buy_start_index':{} ,'buy_exec_index':{},'volume_reate':{},'desc':'{}'",
                                    buy_single_index, buy_exec_index, cls.volume_rate_info[code][0],
                                    params_desc)
                ############记录下单时的数据############
                try:
                    jx_blocks, jx_blocks_by = KPLCodeJXBlockManager().get_jx_blocks_cache(
                        code), KPLCodeJXBlockManager().get_jx_blocks_cache(code, by=True)
                    info = cls.__trade_log_placr_order_info_dict[code]
                    info.set_buy_index(buy_single_index, buy_exec_index)
                    if jx_blocks:
                        info.set_kpl_blocks(list(jx_blocks))
                    elif jx_blocks_by:
                        info.set_kpl_blocks(list(jx_blocks_by))
                    else:
                        info.set_kpl_blocks([])
                    trade_record_log_util.add_place_order_log(code, info)
                except Exception as e:
                    async_log_util.error(logger_l2_error, f"加入买入记录日志出错:{str(e)}")
            except Exception as e:
                async_log_util.exception(logger_l2_error, e)
                l2_log.debug(code, "执行买入异常:{}", str(e))
@@ -929,9 +949,10 @@
            if cancel_index is None:
                cancel_index = total_datas[-1]["index"]
            cls.__LatestCancelIndexManager.set_latest_cancel_index(code, cancel_index)
            # 添加撤单日志记录
            trade_record_log_util.add_cancel_msg_log(code, msg)
            cancel_result = cls.__cancel_buy(code)
            if cancel_result:
                l2_log.trade_record(code, "撤单", "'index':{} , 'msg':'{}'", cancel_index, msg)
                trade_result_manager.real_cancel_success(code, buy_single_index, buy_exec_index, total_datas)
        l2_log.debug(code, "执行撤单结束,原因:{}", msg)
        return True
@@ -1248,6 +1269,12 @@
                max_buy_num_set_count += total_datas[i1]["re"]
            # 有撤单信号,且小于阈值
            if buy_nums >= threshold_num and buy_count >= threshold_count and trigger_buy and max_buy_num_set_count >= big_num_count:
                try:
                    info = cls.__trade_log_placr_order_info_dict[code]
                    info.set_trade_factor(threshold_money, threshold_count, list(max_buy_num_set))
                except Exception as e:
                    async_log_util.error(logger_l2_error, f"记录交易因子出错:{str(e)}")
                return i, buy_nums, buy_count, None, max_buy_num_set
        l2_log.buy_debug(code, "尚未获取到买入执行点,起始计算位置:{} 统计纯买手数:{} 目标纯买手数:{}  统计纯买单数:{} 目标纯买单数:{} 大单数量:{} 目标大单数量:{}",
@@ -1258,7 +1285,27 @@
        return None, buy_nums, buy_count, None, max_buy_num_set
def test_trade_record():
    code = "000333"
    __trade_log_placr_order_info_dict = {code: trade_record_log_util.PlaceOrderInfo()}
    try:
        jx_blocks, jx_blocks_by = KPLCodeJXBlockManager().get_jx_blocks_cache(
            code), KPLCodeJXBlockManager().get_jx_blocks_cache(code, by=True)
        info = __trade_log_placr_order_info_dict[code]
        info.set_buy_index(0, 1)
        if jx_blocks:
            info.set_kpl_blocks(list(jx_blocks))
        elif jx_blocks_by:
            info.set_kpl_blocks(list(jx_blocks_by))
        else:
            info.set_kpl_blocks([])
        trade_record_log_util.add_place_order_log(code, info)
    except:
        pass
if __name__ == "__main__":
    test_trade_record()
    # yesterday_limit_up_data_records = kpl_data_manager.get_current_limit_up_data_records(1)[0][1]
    # yesterday_codes = set([x[0] for x in yesterday_limit_up_data_records])
    # print(yesterday_codes)
l2/l2_log.py
@@ -44,6 +44,7 @@
def d_cancel_debug(code, content, *args):
    __add_async_log(logger_l2_d_cancel, code, content, *args)
# 交易记录
def trade_record(code, type, content, *args):
    if len(args) > 0:
log_module/log_export.py
@@ -1,7 +1,10 @@
import datetime
import hashlib
import json
import logging
import os
import shutil
import time
import constant
from code_attribute import gpcode_manager
@@ -179,26 +182,25 @@
        date = datetime.datetime.now().strftime("%Y-%m-%d")
    index_list = []
    buy_queues = []
    with open("{}/logs/gp/l2/l2_trade_buy_queue.{}.log".format(constant.get_path_prefix(), date), mode='r',
              encoding="utf-8") as f:
        while True:
            line = f.readline()
            if not line:
                break
            time_ = __get_log_time(line).strip()
            if int(time_.replace(":", "")) > int("150000"):
                continue
    path_str = "{}/logs/gp/l2/l2_trade_buy_queue.{}.log".format(constant.get_path_prefix(), date)
    lines = __load_file_content(path_str)
    for line in lines:
        if not line:
            break
        time_ = __get_log_time(line).strip()
        if int(time_.replace(":", "")) > int("150000"):
            continue
            if line.find(f"{code}-[") >= 0:
                buy_queues.append((eval(line.split(f"{code}-")[1]), time_))
        if line.find(f"{code}-[") >= 0:
            buy_queues.append((eval(line.split(f"{code}-")[1]), time_))
            if line.find("获取成交位置成功: code-{}".format(code)) < 0:
                continue
            try:
                index = int(line.split("index-")[1].split(" ")[0])
                index_list.append((index, time_))
            except:
                pass
        if line.find("获取成交位置成功: code-{}".format(code)) < 0:
            continue
        try:
            index = int(line.split("index-")[1].split(" ")[0])
            index_list.append((index, time_))
        except:
            pass
    return index_list, buy_queues
@@ -207,21 +209,20 @@
    if not date:
        date = datetime.datetime.now().strftime("%Y-%m-%d")
    path_str = f"{constant.get_path_prefix()}/logs/gp/l2/cancel/h_cancel.{date}.log"
    lines = __load_file_content(path_str)
    latest_info = None
    if os.path.exists(path_str):
        with open(path_str, mode='r', encoding="utf-8") as f:
            while True:
                line = f.readline()
                if not line:
                    break
                if line.find(f"code-{code}") < 0:
                    continue
                if line.find(f"H级撤单计算结果") < 0:
                    continue
                target_rate = line.split("目标比例:")[1].split(" ")[0].strip()
                cancel_num = line.split("取消计算结果")[1][1:].split("/")[0].strip()
                total_num = line.split("取消计算结果")[1][1:].split("/")[1].split(" ")[0].strip()
                latest_info = (target_rate, round(int(cancel_num) / int(total_num), 2), cancel_num, total_num,)
    for line in lines:
        if not line:
            break
        if line.find(f"code-{code}") < 0:
            continue
        if line.find(f"H级撤单计算结果") < 0:
            continue
        target_rate = line.split("目标比例:")[1].split(" ")[0].strip()
        cancel_num = line.split("取消计算结果")[1][1:].split("/")[0].strip()
        total_num = line.split("取消计算结果")[1][1:].split("/")[1].split(" ")[0].strip()
        latest_info = (target_rate, round(int(cancel_num) / int(total_num), 2), cancel_num, total_num,)
    return latest_info
@@ -278,36 +279,54 @@
    return results
# 加载买入得分记录
def load_buy_score_recod(code):
    path = f"{constant.get_path_prefix()}/logs/gp/trade/trade_record.{tool.get_now_date_str()}.log"
    fdatas = []
    if os.path.exists(path):
        with open(path, 'r', encoding="utf-8") as f:
__log_file_contents = {}
# 加载文件内容
def __load_file_content(path_str, expire_timespace=20):
    md5 = hashlib.md5(path_str.encode(encoding='utf-8')).hexdigest()
    if md5 in __log_file_contents and time.time() - __log_file_contents[md5][0] < expire_timespace:
        return __log_file_contents[md5][1]
    contents = []
    if os.path.exists(path_str):
        with open(path_str, 'r', encoding="utf-8") as f:
            lines = f.readlines()
            for line in lines:
                data_index = line.find(f"code={code}")
                if data_index > 0:
                    time_str = line[11:19]
                    data = line[line.find("data=") + 5:]
                    type = line[line.find("type=") + 5:line.find(" ", line.find("type="))]
                    fdatas.append((time_str, type, eval("{" + data + "}")))
                contents.append(line)
    __log_file_contents[md5] = (time.time(), contents)
    return contents
# 加载买入得分记录
def load_trade_recod(code):
    path = f"{constant.get_path_prefix()}/logs/gp/trade/trade_record.{tool.get_now_date_str()}.log"
    fdatas = []
    lines = __load_file_content(path)
    for line in lines:
        data_index = line.find(f"{code}")
        if data_index > 0:
            line = line.split(" - ")[1]
            time_str = line[line.find("[") + 1:line.find("[") + 9]
            data = line[line.find("]") + 1:].strip()
            data_json = json.loads(data)
            if data_json["code"] != code:
                continue
            type = data_json["type"]
            fdatas.append((time_str, type, data_json["data"]))
    return fdatas
def load_kpl_reason_changes():
    path = f"{constant.get_path_prefix()}/logs/gp/kpl/kpl_limit_up_reason_change.{tool.get_now_date_str()}.log"
    fdatas = []
    if os.path.exists(path):
        with open(path, 'r', encoding="utf-8") as f:
            lines = f.readlines()
            for line in lines:
                if line.find("code-") > 0:
                    data = line[line.find("code-") + 5:]
                    code = data.split(":")[0]
                    from_r = data.split(":")[1].split("-")[0]
                    to_r = eval(data.split(":")[1].split("-")[1])
                    fdatas.append((code, from_r, to_r))
    lines = __load_file_content(path)
    for line in lines:
        if line.find("code-") > 0:
            data = line[line.find("code-") + 5:]
            code = data.split(":")[0]
            from_r = data.split(":")[1].split("-")[0]
            to_r = eval(data.split(":")[1].split("-")[1])
            fdatas.append((code, from_r, to_r))
    return fdatas
@@ -353,7 +372,9 @@
if __name__ == '__main__':
    load_huaxin_local_buy_no()
    datas = load_buy_score_recod("000333")
    for d in datas:
        print(d)
    # print(get_h_cancel_compute_info("603912"))
    # logger_l2_h_cancel.info("test")
output/code_info_output.py
@@ -18,7 +18,7 @@
import l2.l2_data_manager_new
from third_data import kpl_data_manager, kpl_api
from third_data.kpl_data_manager import KPLLimitUpDataRecordManager
from trade import first_code_score_manager, l2_trade_factor, trade_manager, l2_trade_util
from trade import first_code_score_manager, l2_trade_factor, trade_manager, l2_trade_util, trade_record_log_util
from trade.l2_trade_factor import L2TradeFactorUtil
import trade.deal_big_money_manager
@@ -338,7 +338,7 @@
    break_time = limit_up_info[1]
    records = []
    try:
        records = log_export.load_buy_score_recod(code)
        records = log_export.load_trade_recod(code)
    except:
        pass
    records_new = []
@@ -350,32 +350,52 @@
                time_ = record[0]
                type = record[1]
                data = record[2]
                if type == '下单':
                    index += 1
                    temp = f"第{index}次下单:【{time_}】&【{data['score']}分】,{data.get('desc')}"
                    records_new.append(temp)
                    records_new_data.append({"type": 1, "index": index, "time": time_, "score": data['score']})
                elif type == 'S撤':
                    # index':378 , 'rate':0.51 , 'target_rate':0.49
                    pass
                elif type == 'S撤范围':
                    start = format_l2_data(total_datas[data['start_index']])
                    end = format_l2_data(total_datas[data['end_index']])
                    range_seconds = data['range_seconds']
                    temp = f"第{index}次撤单:S撤囊括范围:【起始位:{start}】至【截止位:{end}】囊括时间【{range_seconds}】秒"
                elif type == 'H撤范围':
                    start = format_l2_data(total_datas[data['start_index']])
                    end = format_l2_data(total_datas[data['end_index']])
                    count = data['count']
                    temp = f"H撤囊括范围:【起始位:{start}】至【截止位:{end}】物理笔数共【{count}】笔"
                elif type == 'H撤':
                    # 'start_index':339,'end_index':464, 'count':17
                    pass
                elif type == '撤单':
                    temp = f"第{index}次撤单:【{time_}】{data['msg']}"
                    records_new.append(temp)
                    records_new_data.append({"type": 0, "time": time_, "desc": data['msg']})
                if type == trade_record_log_util.TYPE_PLACE_ORDER:
                    records_new_data.append((time_, "开盘啦推荐原因",
                                             f"{'、'.join(data['kpl_blocks'])}",
                                             None))
                    extra_datas = []
                    if data['big_num_indexes']:
                        big_num_desc = []
                        for i in data['big_num_indexes']:
                            big_num_desc.append(format_l2_data(total_datas[i]))
                        extra_datas.append(f"包含大单:{' & '.join(big_num_desc)}")
                    extra_datas.append(f"M值:{money_desc(data['m_val'])}")
                    extra_datas.append(f"安全笔数:{data['safe_count']}")
                    records_new_data.append((time_, "下单",
                                             f"【{format_l2_data(total_datas[data['buy_single_index']])}】-【{format_l2_data(total_datas[data['buy_exec_index']])}】",
                                             data))
                elif type == trade_record_log_util.TYPE_REAL_PLACE_ORDER_POSITION:
                    records_new_data.append((time_, "实际挂单位", f"【{format_l2_data(data['index'])}】", None))
                elif type == trade_record_log_util.TYPE_CANCEL_WATCH_INDEXES:
                    indexes = data['watch_indexes']
                    if indexes:
                        cancel_type = data['cancel_type']
                        indexes.sort()
                        indexes_data = []
                        for index in indexes:
                            indexes_data.append(format_l2_data(total_datas[index]))
                        desc = f"【{format_l2_data(total_datas[indexes[0]])}】-【{format_l2_data(total_datas[indexes[-1]])}】"
                        if cancel_type == trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_L_DOWN:
                            records_new_data.append((time_, "L撤后囊括", desc, indexes_data))
                        elif cancel_type == trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_L_UP:
                            records_new_data.append((time_, "L撤前囊括", desc, indexes_data))
                        elif cancel_type == trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_H:
                            records_new_data.append((time_, "H撤囊括", desc, indexes_data))
                        elif cancel_type == trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_D:
                            records_new_data.append((time_, "D撤囊括", desc, indexes_data))
                        elif cancel_type == trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_S:
                            records_new_data.append((time_, "S撤囊括", desc, indexes_data))
                elif type == trade_record_log_util.TYPE_FORBIDDEN_BUY:
                    records_new_data.append((time_, "加入黑名单", f"原因:{data['msg']}", None))
                elif type == trade_record_log_util.TYPE_CANT_PLACE_ORDER:
                    records_new_data.append((time_, "不能下单", f"原因:{data['msg']}", None))
                elif type == trade_record_log_util.TYPE_CANCEL:
                    records_new_data.append((time_, "撤单", f"原因:{data['msg']}", None))
            if records_new_data:
                for d in records_new_data:
                    records_new.append(f"【{d[0]}】"+"{:<10}".format(d[1])+d[2])
        except:
            pass
@@ -383,5 +403,5 @@
if __name__ == '__main__':
    plate_info = kpl_api.getStockIDPlate("600748")
    print(plate_info)
    ts = ("0", "1", "2", "3")
    print(','.join(ts[:-1]))
third_data/code_plate_key_manager.py
@@ -19,10 +19,18 @@
# 代码精选板块管理
class KPLCodeJXBlockManager:
    __db = 3
    __redisManager = redis_manager.RedisManager(3)
    __code_blocks = {}
    # 备用
    __code_by_blocks = {}
    __instance = None
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(KPLCodeJXBlockManager, cls).__new__(cls, *args, **kwargs)
        return cls.__instance
    def __get_redis(self):
        return self.__redisManager.getRedis()
@@ -35,10 +43,10 @@
        # 保存前2条数据
        if by:
            RedisUtils.setex(self.__get_redis(), f"kpl_jx_blocks_by-{code}", tool.get_expire(), json.dumps(blocks))
            RedisUtils.setex_async(self.__db, f"kpl_jx_blocks_by-{code}", tool.get_expire(), json.dumps(blocks))
            self.__code_by_blocks[code] = blocks
        else:
            RedisUtils.setex(self.__get_redis(), f"kpl_jx_blocks-{code}", tool.get_expire(), json.dumps(blocks))
            RedisUtils.setex_async(self.__db, f"kpl_jx_blocks-{code}", tool.get_expire(), json.dumps(blocks))
            self.__code_blocks[code] = blocks
    # 获取精选板块
trade/huaxin/huaxin_trade_order_processor.py
@@ -10,13 +10,14 @@
from l2.l2_data_manager import TradePointManager
from log_module import async_log_util
from log_module.log import logger_trade, hx_logger_trade_debug
from trade import trade_manager
from trade import trade_manager, trade_record_log_util
from trade.huaxin.huaxin_trade_record_manager import TradeOrderIdManager
from utils import huaxin_util, tool
class HuaxinOrderEntity:
    def __init__(self, code, orderStatus, orderRef, accountID, orderSysID,direction=None, insertDate=None, insertTime=None,
    def __init__(self, code, orderStatus, orderRef, accountID, orderSysID, direction=None, insertDate=None,
                 insertTime=None,
                 acceptTime=None):
        self.code = code
        self.orderStatus = orderStatus
@@ -130,6 +131,10 @@
                    cancel_buy_strategy.set_real_place_position(order.code,
                                                                new_place_order_index,
                                                                buy_single_index)
                    trade_record_log_util.add_real_place_order_position_log(order.code,
                                                                            new_place_order_index,
                                                                            buy_single_index)
            elif huaxin_util.is_canceled(order.orderStatus) or huaxin_util.is_deal(
                    order.orderStatus):
                # 已经撤单/已经成交,需要处理临时保存的系统订单号
trade/l2_trade_util.py
@@ -3,6 +3,7 @@
from db.redis_manager_delegate import RedisUtils
from log_module import async_log_util
from log_module.log import logger_trade
from trade import trade_record_log_util
from utils import tool
__redis_manager = redis_manager.RedisManager(2)
@@ -129,6 +130,8 @@
# 禁止代码交易
def forbidden_trade(code, msg=None):
    if not is_in_forbidden_trade_codes(code):
        trade_record_log_util.add_forbidden_buy_log(code, msg)
    add_to_forbidden_trade_codes(code)
    async_log_util.warning(logger_trade, f"{code}加入黑名单原因:{msg}")
    # l2_data_manager.remove_from_l2_fixed_codes(code)
trade/trade_manager.py
@@ -42,7 +42,7 @@
# 买成功
TRADE_STATE_BUY_SUCCESS = 12
guiTrade = trade_gui.THSGuiTrade() if trade_gui is not None else None
guiTrade = None#trade_gui.THSGuiTrade() if trade_gui is not None else None
latest_trade_delegate_data = []
trade/trade_record_log_util.py
New file
@@ -0,0 +1,135 @@
"""
交易记录日志工具
"""
# 下单信息
import json
import pickle
from log_module import async_log_util
from log_module.log import logger_trade_record
from third_data.code_plate_key_manager import KPLCodeJXBlockManager
TYPE_PLACE_ORDER = "place_order"  # 下单
TYPE_REAL_PLACE_ORDER_POSITION = "real_place_order_position"  # 真实下单位置
TYPE_CANCEL_WATCH_INDEXES = "cancel_watch_indexes"  # 撤单监听位置
TYPE_FORBIDDEN_BUY = "forbidden_buy"  # 禁止买入
TYPE_CANT_PLACE_ORDER = "can_not_place_order"  # 不能下单
TYPE_CANCEL = "cancel"  # 撤单
class PlaceOrderInfo(object):
    def __init__(self, buy_single_index=None, buy_exec_index=None, m_val=None, safe_count=None, big_num_indexes=None,
                 kpl_blocks=None):
        self.buy_single_index = buy_single_index
        self.buy_exec_index = buy_exec_index
        self.m_val = m_val
        self.safe_count = safe_count
        self.big_num_indexes = big_num_indexes
        self.kpl_blocks = kpl_blocks
    def set_buy_index(self, buy_single_index, buy_exec_index):
        self.buy_single_index = buy_single_index
        self.buy_exec_index = buy_exec_index
    def set_trade_factor(self, m_val, safe_count, big_num_indexes):
        self.m_val = m_val
        self.safe_count = safe_count
        self.big_num_indexes = big_num_indexes
    def set_kpl_blocks(self, kpl_blocks):
        self.kpl_blocks = kpl_blocks
    def to_json_str(self):
        return json.dumps(vars(self))
    def to_dict(self):
        return vars(self)
    @classmethod
    def to_object(cls, json_str: str):
        d = json.loads(json_str)
        return PlaceOrderInfo(**d)
# 撤单揽括信息
class CancelWatchIndexesInfo(object):
    CANCEL_TYPE_H = "h_cancel"
    CANCEL_TYPE_S = "s_cancel"
    CANCEL_TYPE_L_UP = "l_cancel_up"
    CANCEL_TYPE_L_DOWN = "l_cancel_down"
    CANCEL_TYPE_D = "d_cancel"
    def __init__(self, cancel_type, watch_indexes: list):
        self.cancel_type = cancel_type
        self.watch_indexes = watch_indexes
    def to_json_str(self):
        return json.dumps(vars(self))
    def to_dict(self):
        return vars(self)
    @classmethod
    def to_object(cls, json_str: str):
        d = json.loads(json_str)
        return CancelWatchIndexesInfo(**d)
# 添加日志
def __add_log(type, code, data):
    try:
        fdata = {"code": code, "type": type, "data": data}
        async_log_util.info(logger_trade_record, json.dumps(fdata))
    except:
        pass
# 添加下单日志
def add_place_order_log(code, info: PlaceOrderInfo):
    __add_log(TYPE_PLACE_ORDER, code, info.to_dict())
# 加入禁止买入
def add_forbidden_buy_log(code, msg):
    __add_log(TYPE_FORBIDDEN_BUY, code, {"msg": msg})
# 不能买
def add_cant_place_order_log(code, msg):
    __add_log(TYPE_CANT_PLACE_ORDER, code, {"msg": msg})
# 真实下单位置
def add_real_place_order_position_log(code, index, buy_single_index):
    __add_log(TYPE_REAL_PLACE_ORDER_POSITION, code, {"index": index, "buy_single_index": buy_single_index})
# 撤单策略监听位置
def add_cancel_watch_indexes_log(code, info: CancelWatchIndexesInfo):
    __add_log(TYPE_CANCEL_WATCH_INDEXES, code, info.to_dict())
# 添加撤单信息
def add_cancel_msg_log(code, msg):
    __add_log(TYPE_CANCEL, code, {"msg": msg})
if __name__ == "__main__":
    code = "000333"
    __trade_log_placr_order_info_dict = {code: PlaceOrderInfo()}
    try:
        jx_blocks, jx_blocks_by = KPLCodeJXBlockManager().get_jx_blocks_cache(
            code), KPLCodeJXBlockManager().get_jx_blocks_cache(code, by=True)
        info = __trade_log_placr_order_info_dict[code]
        info.set_buy_index(0, 1)
        if jx_blocks:
            info.set_kpl_blocks(list(jx_blocks))
        elif jx_blocks_by:
            info.set_kpl_blocks(list(jx_blocks_by))
        else:
            info.set_kpl_blocks([])
        add_place_order_log(code, info)
    except Exception as e:
        pass