Administrator
2025-01-06 6567e8cd1fb11ea10912bb3ac5bf2965c74c0e4b
api/outside_api_command_callback.py
@@ -18,7 +18,8 @@
from code_attribute import gpcode_manager, code_volumn_manager, zyltgb_util
from code_attribute.code_data_util import ZYLTGBUtil
from code_attribute.code_l1_data_manager import L1DataManager
from code_attribute.gpcode_manager import CodePrePriceManager, CodesNameManager, WantBuyCodesManager
from code_attribute.gpcode_manager import CodePrePriceManager, CodesNameManager, WantBuyCodesManager, \
    HumanRemoveForbiddenManager
from db import mysql_data_delegate as mysql_data, redis_manager_delegate as redis_manager
from db.redis_manager_delegate import RedisUtils
from huaxin_client import l1_subscript_codes_manager
@@ -35,11 +36,12 @@
    logger_trade, logger_trade_position_api_request, logger_request_api, \
    logger_real_place_order_position, logger_device
from output import l2_output_util
from third_data import kpl_util, history_k_data_manager, huaxin_l1_data_manager, third_blocks_manager, kpl_data_manager
from third_data.code_plate_key_manager import CodePlateKeyBuyManager, KPLCodeJXBlockManager, RealTimeKplMarketData, \
    RadicalBuyBlockManager
from third_data import kpl_util, history_k_data_manager, huaxin_l1_data_manager, third_blocks_manager, kpl_data_manager, \
    history_k_data_util
from third_data.code_plate_key_manager import KPLCodeJXBlockManager, RealTimeKplMarketData
from third_data.history_k_data_manager import HistoryKDataManager
from third_data.history_k_data_util import JueJinApi, HistoryKDatasUtils
from third_data.kpl_data_constant import LimitUpDataConstant
from third_data.kpl_data_manager import KPLDataManager
from third_data.kpl_limit_up_data_manager import CodeLimitUpSequenceManager
from third_data.kpl_util import KPLDataType
@@ -47,12 +49,15 @@
from trade import trade_manager, l2_trade_util, trade_data_manager, trade_constant
import l2_data_util as l2_data_util_old
from trade.buy_money_count_setting import BuyMoneyAndCountSetting, RadicalBuyBlockCodeCountManager
from trade.buy_radical import block_special_codes_manager, radical_buy_data_manager
from trade.huaxin import huaxin_trade_api, huaxin_trade_data_update, \
    huaxin_trade_record_manager, huaxin_trade_order_processor, huaxin_sell_util
from trade.huaxin.huaxin_trade_record_manager import PositionManager, DealRecordManager, DelegateRecordManager
from trade.buy_radical.radical_buy_data_manager import RadicalBuyBlockManager, BeforeSubDealBigOrderManager
from trade.sell import sell_manager
from trade.sell.sell_rule_manager import TradeRuleManager, SellRule
from trade.trade_data_manager import RadicalBuyDealCodesManager
from trade.trade_manager import TradeTargetCodeModeManager, AutoCancelSellModeManager
from settings.trade_setting import MarketSituationManager, TradeBlockBuyModeManager
from utils import socket_util, data_export_util, tool, huaxin_util, output_util, global_util
@@ -93,7 +98,7 @@
    def __cancel_not_deal_order(self, code, order_ref, timeout=3):
        time.sleep(timeout)
        # 撤买单
        huaxin_trade_api.cancel_order(1, code, "", orderRef=order_ref)
        huaxin_trade_api.cancel_order(huaxin_trade_api.TRADE_DIRECTION_BUY, code, "", orderRef=order_ref)
    # 交易
    def OnTrade(self, client_id, request_id, data):
@@ -288,8 +293,10 @@
            if code_list_type == outside_api_command_manager.CODE_LIST_WANT:
                if operate == outside_api_command_manager.OPERRATE_SET:
                    gpcode_manager.WantBuyCodesManager().add_code(code)
                    # 加想买单要从黑名单移除
                    l2_trade_util.remove_from_forbidden_trade_codes(code)
                    if l2_trade_util.is_in_forbidden_trade_codes(code):
                        l2_trade_util.remove_from_forbidden_trade_codes(code)
                        # 加想买单要从黑名单移除
                        HumanRemoveForbiddenManager().add_code(code)
                    name = gpcode_manager.get_code_name(code)
                    if not name:
                        results = HistoryKDatasUtils.get_gp_codes_names([code])
@@ -312,8 +319,9 @@
                                                                            cancel_type=trade_constant.CANCEL_TYPE_HUMAN)
                    except Exception as e:
                        logger_debug.exception(e)
                    l2_trade_util.forbidden_trade(code, msg="手动加入 trade_server")
                    l2_trade_util.forbidden_trade(code, msg="手动加入 trade_server", force=True)
                    WantBuyCodesManager().remove_code(code)
                    HumanRemoveForbiddenManager().remove_code(code)
                    name = gpcode_manager.get_code_name(code)
                    if not name:
                        results = HistoryKDatasUtils.get_gp_codes_names([code])
@@ -321,7 +329,7 @@
                            gpcode_manager.CodesNameManager.add_first_code_name(code, results[code])
                elif operate == outside_api_command_manager.OPERRATE_DELETE:
                    l2_trade_util.remove_from_forbidden_trade_codes(code)
                    WantBuyCodesManager().add_code(code)
                    HumanRemoveForbiddenManager().add_code(code)
                elif operate == outside_api_command_manager.OPERRATE_GET:
                    codes = gpcode_manager.BlackListCodeManager().list_codes_cache()
                    datas = []
@@ -384,6 +392,7 @@
            elif code_list_type == outside_api_command_manager.CODE_LIST_GREEN:
                if operate == outside_api_command_manager.OPERRATE_SET:
                    gpcode_manager.GreenListCodeManager().add_code(code)
                    gpcode_manager.WantBuyCodesManager().add_code(code)
                    name = gpcode_manager.get_code_name(code)
                    if not name:
                        results = HistoryKDatasUtils.get_gp_codes_names([code])
@@ -391,6 +400,7 @@
                            gpcode_manager.CodesNameManager.add_first_code_name(code, results[code])
                elif operate == outside_api_command_manager.OPERRATE_DELETE:
                    gpcode_manager.GreenListCodeManager().remove_code(code)
                    gpcode_manager.WantBuyCodesManager().remove_code(code)
                elif operate == outside_api_command_manager.OPERRATE_GET:
                    codes = gpcode_manager.GreenListCodeManager().list_codes_cache()
                    datas = []
@@ -478,7 +488,8 @@
        try:
            fdata = {}
            try:
                date = JueJinApi.get_previous_trading_date(tool.get_now_date_str())
                date = HistoryKDatasUtils.get_trading_dates(tool.date_sub(tool.get_now_date_str(), 10),
                                                            tool.get_now_date_str())
                if date:
                    fdata["juejin"] = 1
            except Exception as e:
@@ -535,14 +546,10 @@
            # 获取今日K线的更新数量
            try:
                dates = HistoryKDatasUtils.get_latest_trading_date_cache(5)
                latest_trading_date = None
                if dates:
                    latest_trading_date = dates[0]
                if latest_trading_date is None:
                    raise Exception("没有获取到上一个交易日的日期")
                latest_trading_date = history_k_data_util.get_k_bar_dead_date()
                codes = HistoryKDataManager().get_history_bars_codes(latest_trading_date)
                count = len(codes)
                logger_debug.info(f"K线代码数量:{count}")
                fdata["today_history_k_bar_count"] = count
            except Exception as e:
                logger_debug.exception(e)
@@ -880,6 +887,8 @@
                                order_begin_pos = OrderBeginPosInfo(buy_single_index=0, buy_exec_index=0)
                            l2_data_util.load_l2_data(code)
                            total_datas = l2_data_util.local_today_datas.get(code)
                            if not total_datas:
                                continue
                            trade_index, is_default = transaction_progress.TradeBuyQueue().get_traded_index(code)
                            if trade_index is None:
                                trade_index = 0
@@ -930,7 +939,7 @@
                            limit_up_price = gpcode_manager.get_limit_up_price(code)
                            buy1_money = Buy1PriceManager().get_latest_buy1_money(code)
                            if buy1_money is None:
                                buy1_money = 0
                                buy1_money = 1
                            # 获取已经成交的大单数量
                            total_big_num = 0
                            total_big_count = 0
@@ -1013,7 +1022,7 @@
                                    real_place_order_after_num += val["num"]
                            # 获取当日的量比
                            volume_rate = code_volumn_manager.get_volume_rate(code)
                            volume_rate = code_volumn_manager.CodeVolumeManager().get_volume_rate(code)
                            # 是否需要注意
                            need_pay_attention = (total_left_count <= 10 or total_left_num * float(
@@ -1071,7 +1080,7 @@
                                     "pay_attention": need_pay_attention,
                                     "trade_progress_percent": round(
                                         total_left_num * float(limit_up_price) * 100 * 100 / buy1_money, 2),  # 成交进度比例
                                     "limit_up_price": float(gpcode_manager.get_limit_up_price(code)),
                                     "limit_up_price": gpcode_manager.get_limit_up_price_as_num(code),
                                     "is_near_big_order": is_near_big_order,
                                     "block": '',
                                     "trade_queue": []
@@ -1079,10 +1088,18 @@
                            limit_up_data = kpl_data_manager.KPLLimitUpDataRecordManager.record_code_dict.get(code)
                            # 获取当前板块
                            try:
                                limit_up_sequence = CodeLimitUpSequenceManager.get_current_limit_up_sequence(code)
                                if limit_up_sequence:
                                    fdata[
                                        'block'] = f"{limit_up_sequence[0]}-{limit_up_sequence[1]}({limit_up_sequence[2]}&{limit_up_sequence[2] - limit_up_sequence[3]})"
                                limit_up_sequences = CodeLimitUpSequenceManager.get_current_limit_up_sequence(code)
                                if limit_up_sequences:
                                    buy_blocks = RadicalBuyDealCodesManager().get_code_blocks(code)
                                    blocks_info = []
                                    for limit_up_sequence in limit_up_sequences:
                                        # 获取代码下单的板块
                                        if buy_blocks and limit_up_sequence[0] not in buy_blocks:
                                            continue
                                        blocks_info.append(
                                            f"{limit_up_sequence[0]}-{limit_up_sequence[1]}({limit_up_sequence[2]}&{limit_up_sequence[2] - limit_up_sequence[3]})")
                                    if buy_blocks:
                                        fdata['block'] = "/".join(blocks_info)
                            except:
                                pass
                            # 获取涨停时间
@@ -1101,6 +1118,14 @@
                                zyltgb = global_util.zyltgb_map.get(code)
                                if zyltgb is not None:
                                    fdata['zyltgb'] = output_util.money_desc(zyltgb)
                            except:
                                pass
                            try:
                                if order_begin_pos:
                                    fdata['mode'] = order_begin_pos.mode
                                else:
                                    fdata['mode'] = -1
                            except:
                                pass
@@ -1172,8 +1197,8 @@
            elif ctype == "set_per_code_buy_money":
                # 设置单只票的买入金额
                money = data["money"]
                if money > 30000:
                    raise Exception("最多只能设置3w")
                if money > 50000:
                    raise Exception("最多只能设置5w")
                constant.BUY_MONEY_PER_CODE = money
                self.send_response({"code": 0, "data": {"money": constant.BUY_MONEY_PER_CODE}}, client_id, request_id)
            elif ctype == "get_per_code_buy_money":
@@ -1183,6 +1208,8 @@
                kpl_data_manager.PullTask.repaire_pull_task()
                # 修复数据服务
                server_util.repaire_data_server()
                # 任务修复
                huaxin_trade_data_update.repaire_task()
                self.send_response({"code": 0, "data": {}}, client_id, request_id)
            elif ctype == "get_trade_queue":
                code = data["code"]
@@ -1196,9 +1223,16 @@
                # 获取大单成交列表
                code = data["code"]
                data_list = BigOrderDealManager().get_total_buy_money_list(code)
                bigger_money = l2_data_util_old.get_big_money_val(float(gpcode_manager.get_limit_up_price(code)),
                bigger_money = l2_data_util_old.get_big_money_val(gpcode_manager.get_limit_up_price_as_num(code),
                                                                  tool.is_ge_code(code))
                fdatas = []
                # 加载订阅之前的大单
                pre_deals = BeforeSubDealBigOrderManager().get_deal_big_order_money_list(code)
                if pre_deals:
                    for d in pre_deals:
                        if d[0] < bigger_money:
                            continue
                        fdatas.append(d[0])
                for d in data_list:
                    if d < bigger_money:
                        continue
@@ -1244,11 +1278,9 @@
                source_origin_dict = copy.deepcopy(CodeThirdBlocksManager().get_source_blocks_origin(code))
                if not source_origin_dict:
                    source_origin_dict = {}
                kpl_blocks = RadicalBuyBlockManager.get_code_kpl_blocks(code)
                kpl_blocks = set()
                if kpl_blocks is None:
                    kpl_blocks = set()
                if not kpl_blocks:
                    KPLCodeJXBlockManager().load_jx_blocks_radical(code)
                filter_blocks, match_blocks = RadicalBuyBlockManager.get_code_blocks(code)
                source_origin_dict[SOURCE_TYPE_KPL] = kpl_blocks
@@ -1256,7 +1288,9 @@
                data = {
                    "blocks": {},
                    "origin_blocks": {},
                    "match_blocks": [list(filter_blocks), list(match_blocks)]
                    "match_blocks": [list(filter_blocks), list(match_blocks)],
                    # 板块净流入情况
                    "block_in_moneys": [RealTimeKplMarketData.get_block_info_at_block_in(b) for b in filter_blocks]
                }
                for s in source_origin_dict:
                    data["origin_blocks"][s] = list(source_origin_dict[s])
@@ -1270,6 +1304,10 @@
                # 设置买入金额和数量
                normal = data["normal"]
                radical = data["radical"]
                default_buy_money = data["default_buy_money"]
                if int(default_buy_money) not in constant.AVAILABLE_BUY_MONEYS:
                    raise Exception("默认金额不在预设金额内")
                constant.BUY_MONEY_PER_CODE = default_buy_money
                BuyMoneyAndCountSetting().set_normal_buy_data(normal[0], json.loads(normal[1]))
                BuyMoneyAndCountSetting().set_radical_buy_data(radical[0], json.loads(radical[1]))
                data = {
@@ -1284,7 +1322,8 @@
                data = {
                    "normal": BuyMoneyAndCountSetting().get_normal_buy_setting(),
                    "radical": BuyMoneyAndCountSetting().get_radical_buy_setting(),
                    "moneys": constant.AVAILABLE_BUY_MONEYS
                    "moneys": constant.AVAILABLE_BUY_MONEYS,
                    "default_buy_money": constant.BUY_MONEY_PER_CODE
                }
                self.send_response({"code": 0, "data": data, "msg": f""},
                                   client_id,
@@ -1304,6 +1343,89 @@
                self.send_response({"code": 0, "data": data, "msg": f""},
                                   client_id,
                                   request_id)
            elif ctype == "get_place_order_settings":
                # 获取买入下单设置
                data = {
                    "radical_buy": {"price": (constant.MIN_CODE_RADICAL_BUY_PRICE, constant.MAX_CODE_RADICAL_BUY_PRICE),
                                    "zyltgb": constant.RADICAL_BUY_ZYLTGB_AS_YI_RANGES,
                                    "top_block_count_by_market_strong": constant.RADICAL_BUY_TOP_IN_COUNT_BY_MARKET_STRONG,
                                    "special_codes_max_block_in_rank": constant.RADICAL_BUY_TOP_IN_INDEX_WITH_SPECIAL
                                    }}
                self.send_response({"code": 0, "data": data, "msg": f""},
                                   client_id,
                                   request_id)
            elif ctype == "set_place_order_settings":
                radical_buy = data.get("radical_buy")
                if radical_buy:
                    radical_buy = json.loads(radical_buy)
                    constant.MIN_CODE_RADICAL_BUY_PRICE = radical_buy["price"][0]
                    constant.MAX_CODE_RADICAL_BUY_PRICE = radical_buy["price"][1]
                    constant.RADICAL_BUY_ZYLTGB_AS_YI_RANGES = radical_buy["zyltgb"]
                    if radical_buy.get("top_block_count_by_market_strong"):
                        constant.RADICAL_BUY_TOP_IN_COUNT_BY_MARKET_STRONG = radical_buy.get(
                            "top_block_count_by_market_strong")
                    if radical_buy.get("special_codes_max_block_in_rank"):
                        constant.RADICAL_BUY_TOP_IN_INDEX_WITH_SPECIAL = radical_buy.get(
                            "special_codes_max_block_in_rank")
                self.send_response({"code": 0, "data": {}, "msg": f""},
                                   client_id,
                                   request_id)
            elif ctype == "get_buy_open_limit_up_codes":
                # 获取隔夜单排1的代码
                codes = gpcode_manager.BuyOpenLimitUpCodeManager().get_codes()
                if not codes:
                    codes = set()
                self.send_response({"code": 0, "data": list(codes), "msg": f""},
                                   client_id,
                                   request_id)
            elif ctype == "set_buy_open_limit_up_codes":
                # 设置隔夜单排1的代码
                codes = data.get("codes")
                codes = json.loads(codes)
                gpcode_manager.BuyOpenLimitUpCodeManager().set_codes(set(codes))
                self.send_response({"code": 0, "data": list(codes), "msg": f""},
                                   client_id,
                                   request_id)
            elif ctype == "async_radical_buy_special_codes":
                # 同步扫入买的辨识度代码
                count = block_special_codes_manager.update_block_special_codes()
                self.send_response({"code": 0, "msg": f"更新成功数量:{count}"},
                                   client_id,
                                   request_id)
            elif ctype == "get_same_block_limit_up_codes_count":
                # 获取相同板块的涨停代码数量
                codes = data.get("codes")
                codes = json.loads(codes)
                block_codes = {}
                for code in codes:
                    # 获取板块
                    fblocks, before_fblocks = RadicalBuyBlockManager.get_code_blocks(code)
                    # 获取板块历史涨停
                    for b in fblocks:
                        codes = LimitUpDataConstant.get_history_limit_up_block_codes(b)
                        if codes:
                            if code not in block_codes:
                                block_codes[code] = {}
                            block_codes[code][b] = len(codes)
                self.send_response({"code": 0, "data": block_codes},
                                   client_id,
                                   request_id)
            elif ctype == "test_place_order":
                # 获取相同板块的涨停代码数量
                code = data.get("code")
                # total_datas = l2_data_util.local_today_datas.get(code)
                # trade_manager.test_order(code, total_datas[-1], total_datas[-1]["index"])
                radical_buy_data_manager.pull_pre_deal_big_orders(code)
                self.send_response({"code": 0, "data": {}},
                                   client_id,
                                   request_id)
        except Exception as e:
            logging.exception(e)