From 5adedb7c797ad08b7607c56e8255c21609c97000 Mon Sep 17 00:00:00 2001
From: Administrator <admin@example.com>
Date: 星期一, 15 四月 2024 00:07:31 +0800
Subject: [PATCH] 新版深证下单完善

---
 l2/l2_data_manager_new.py |  240 ++++++++++++++++++++++++++++++++++-------------------------
 1 files changed, 139 insertions(+), 101 deletions(-)

diff --git a/l2/l2_data_manager_new.py b/l2/l2_data_manager_new.py
index 439ba06..28b74f3 100644
--- a/l2/l2_data_manager_new.py
+++ b/l2/l2_data_manager_new.py
@@ -1,4 +1,5 @@
 import logging
+import threading
 import time as t
 
 from code_attribute import big_money_num_manager, code_volumn_manager, code_data_util, industry_codes_sort, \
@@ -19,7 +20,7 @@
 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_record_log_util
 from l2 import l2_data_manager, l2_log, l2_data_source_util, code_price_manager, \
-    transaction_progress, cancel_buy_strategy
+    transaction_progress, cancel_buy_strategy, place_order_single_data_manager
 from l2.cancel_buy_strategy import SCancelBigNumComputer, HourCancelBigNumComputer, DCancelBigNumComputer, \
     LCancelBigNumComputer, LatestCancelIndexManager, LCancelRateManager, GCancelBigNumComputer
 from l2.l2_data_manager import L2DataException, OrderBeginPosInfo
@@ -244,6 +245,9 @@
     __MarketSituationManager = MarketSituationManager()
     __re_compute_threading_pool = concurrent.futures.ThreadPoolExecutor(max_workers=10)
 
+    # 涔板叆閿�
+    __buy_lock_dict = {}
+
     # 鑾峰彇浠g爜璇勫垎
     @classmethod
     def get_code_scores(cls):
@@ -325,8 +329,8 @@
             limit_up_price = gpcode_manager.get_limit_up_price(code)
             if limit_up_price:
                 limit_up_price = round(float(limit_up_price), 2)
-            if trade_price_info and limit_up_price and trade_price_info[0] == limit_up_price:
-                filter_limit_up_sell = True
+            # if trade_price_info and limit_up_price and trade_price_info[0] == limit_up_price:
+            #     filter_limit_up_sell = True
             datas = l2_huaxin_util.get_format_l2_datas(code, origin_datas, limit_up_price, _start_index,
                                                        filter_limit_up_sell)
             __start_time = round(t.time() * 1000)
@@ -399,9 +403,10 @@
                     try:
                         for d in add_datas:
                             if L2DataUtil.is_limit_up_price_sell(d['val']):
-                                L2TradeSingleDataProcessor.add_l2_delegate_limit_up_sell(code,d)
-                            elif  L2DataUtil.is_limit_up_price_sell_cancel(d['val']):
-                                L2TradeSingleDataProcessor.add_l2_delegate_limit_up_sell_cancel(code,d['val']['orderNo'])
+                                L2TradeSingleDataProcessor.add_l2_delegate_limit_up_sell(code, d)
+                            elif L2DataUtil.is_limit_up_price_sell_cancel(d['val']):
+                                L2TradeSingleDataProcessor.add_l2_delegate_limit_up_sell_cancel(code,
+                                                                                                d['val']['orderNo'])
                     except Exception as e:
                         logger_debug.exception(e)
                 except:
@@ -644,89 +649,103 @@
             pass
 
     @classmethod
+    def start_buy(cls, code, last_data, last_data_index, is_first_code):
+        cls.__buy(code, 0, last_data, last_data_index, is_first_code)
+
+    @classmethod
     def __buy(cls, code, capture_timestamp, last_data, last_data_index, is_first_code):
-        __start_time = tool.get_now_timestamp()
-        can, need_clear_data, reason = False, False, ""
-        if not is_first_code:
-            can, need_clear_data, reason = cls.__can_buy(code)
-        else:
-            can, need_clear_data, reason = cls.__can_buy_first(code)
+        # 娣诲姞涔板叆閿�
+        if code not in cls.__buy_lock_dict:
+            cls.__buy_lock_dict[code] = threading.Lock()
 
-        # __start_time = l2_data_log.l2_time(code, tool.get_now_timestamp() - __start_time, "鏈�鍚庡垽鏂槸鍚﹁兘涓嬪崟", force=True)
-        # 鍒犻櫎铏氭嫙涓嬪崟
-        if code in cls.unreal_buy_dict:
-            cls.unreal_buy_dict.pop(code)
+        with cls.__buy_lock_dict[code]:
+            # 鍒ゆ柇鏄惁鍙互涓嬪崟锛屼笉澶勪簬鍙笅鍗曠姸鎬侀渶瑕佽繑鍥�
+            state = cls.__CodesTradeStateManager.get_trade_state_cache(code)
+            if state == trade_manager.TRADE_STATE_BUY_DELEGATED or state == trade_manager.TRADE_STATE_BUY_PLACE_ORDER or state == trade_manager.TRADE_STATE_BUY_SUCCESS:
+                # 涓嶅浜庡彲涓嬪崟鐘舵��
+                return False
+            __start_time = tool.get_now_timestamp()
+            can, need_clear_data, reason = False, False, ""
+            if not is_first_code:
+                can, need_clear_data, reason = cls.__can_buy(code)
+            else:
+                can, need_clear_data, reason = cls.__can_buy_first(code)
 
-        order_begin_pos = cls.__get_order_begin_pos(
-            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, order_begin_pos.buy_single_index,
-                                                         order_begin_pos.buy_exec_index,
-                                                         local_today_datas.get(code))
-            return False
-        else:
-            l2_log.debug(code, "鍙互涓嬪崟锛屽師鍥狅細{}", reason)
-            try:
-                l2_log.debug(code, "寮�濮嬫墽琛屼拱鍏�")
-                trade_manager.start_buy(code, capture_timestamp, last_data,
-                                        last_data_index, order_begin_pos.mode, order_begin_pos.buy_exec_index)
-                l2_log.debug(code, "鎵ц涔板叆鎴愬姛")
-                ################涓嬪崟鎴愬姛澶勭悊################
-                trade_result_manager.real_buy_success(code, cls.__TradePointManager)
-                l2_log.debug(code, "澶勭悊涔板叆鎴愬姛1")
-                cancel_buy_strategy.set_real_place_position(code, local_today_datas.get(code)[-1]["index"],
-                                                            order_begin_pos.buy_single_index, is_default=True)
-                l2_log.debug(code, "澶勭悊涔板叆鎴愬姛2")
-                params_desc = cls.__l2PlaceOrderParamsManagerDict[code].get_buy_rank_desc()
-                l2_log.debug(code, params_desc)
-                ############璁板綍涓嬪崟鏃剁殑鏁版嵁############
+            # __start_time = l2_data_log.l2_time(code, tool.get_now_timestamp() - __start_time, "鏈�鍚庡垽鏂槸鍚﹁兘涓嬪崟", force=True)
+            # 鍒犻櫎铏氭嫙涓嬪崟
+            if code in cls.unreal_buy_dict:
+                cls.unreal_buy_dict.pop(code)
+
+            order_begin_pos = cls.__get_order_begin_pos(
+                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, order_begin_pos.buy_single_index,
+                                                             order_begin_pos.buy_exec_index,
+                                                             local_today_datas.get(code))
+                return False
+            else:
+                l2_log.debug(code, "鍙互涓嬪崟锛屽師鍥狅細{}", reason)
                 try:
-                    jx_blocks, jx_blocks_by = KPLCodeJXBlockManager().get_jx_blocks_cache(
-                        code), KPLCodeJXBlockManager().get_jx_blocks_cache(code, by=True)
-                    if jx_blocks:
-                        jx_blocks = jx_blocks[0]
-                    if jx_blocks_by:
-                        jx_blocks_by = jx_blocks_by[0]
+                    l2_log.debug(code, "寮�濮嬫墽琛屼拱鍏�")
+                    trade_manager.start_buy(code, capture_timestamp, last_data,
+                                            last_data_index, order_begin_pos.mode, order_begin_pos.buy_exec_index)
+                    l2_log.debug(code, "鎵ц涔板叆鎴愬姛")
+                    ################涓嬪崟鎴愬姛澶勭悊################
+                    trade_result_manager.real_buy_success(code, cls.__TradePointManager)
+                    l2_log.debug(code, "澶勭悊涔板叆鎴愬姛1")
+                    cancel_buy_strategy.set_real_place_position(code, local_today_datas.get(code)[-1]["index"],
+                                                                order_begin_pos.buy_single_index, is_default=True)
+                    l2_log.debug(code, "澶勭悊涔板叆鎴愬姛2")
+                    params_desc = cls.__l2PlaceOrderParamsManagerDict[code].get_buy_rank_desc()
+                    l2_log.debug(code, params_desc)
+                    ############璁板綍涓嬪崟鏃剁殑鏁版嵁############
+                    try:
+                        jx_blocks, jx_blocks_by = KPLCodeJXBlockManager().get_jx_blocks_cache(
+                            code), KPLCodeJXBlockManager().get_jx_blocks_cache(code, by=True)
+                        if jx_blocks:
+                            jx_blocks = jx_blocks[0]
+                        if jx_blocks_by:
+                            jx_blocks_by = jx_blocks_by[0]
 
-                    info = cls.__trade_log_placr_order_info_dict[code]
-                    info.mode = order_begin_pos.mode
-                    info.set_buy_index(order_begin_pos.buy_single_index, order_begin_pos.buy_exec_index)
-                    info.set_sell_info(order_begin_pos.sell_info)
-                    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([])
-                    can_buy_result = CodePlateKeyBuyManager.can_buy(code)
-                    if can_buy_result:
-                        if not can_buy_result[0] and can_buy_result[1]:
-                            info.set_kpl_match_blocks(["鐙嫍"])
-                        elif not can_buy_result[0] and not can_buy_result[1]:
-                            info.set_kpl_match_blocks(["闈炵嫭鑻椾笉婊¤冻韬綅"])
+                        info = cls.__trade_log_placr_order_info_dict[code]
+                        info.mode = order_begin_pos.mode
+                        info.set_buy_index(order_begin_pos.buy_single_index, order_begin_pos.buy_exec_index)
+                        info.set_sell_info(order_begin_pos.sell_info)
+                        if jx_blocks:
+                            info.set_kpl_blocks(list(jx_blocks))
+                        elif jx_blocks_by:
+                            info.set_kpl_blocks(list(jx_blocks_by))
                         else:
-                            temps = []
-                            temps.extend(can_buy_result[0])
-                            if can_buy_result[5]:
-                                temps.append(f"婵�杩涗拱鍏ワ細{can_buy_result[5]}")
-                            info.set_kpl_match_blocks(temps)
-                    trade_record_log_util.add_place_order_log(code, info)
+                            info.set_kpl_blocks([])
+                        can_buy_result = CodePlateKeyBuyManager.can_buy(code)
+                        if can_buy_result:
+                            if not can_buy_result[0] and can_buy_result[1]:
+                                info.set_kpl_match_blocks(["鐙嫍"])
+                            elif not can_buy_result[0] and not can_buy_result[1]:
+                                info.set_kpl_match_blocks(["闈炵嫭鑻椾笉婊¤冻韬綅"])
+                            else:
+                                temps = []
+                                temps.extend(can_buy_result[0])
+                                if can_buy_result[5]:
+                                    temps.append(f"婵�杩涗拱鍏ワ細{can_buy_result[5]}")
+                                info.set_kpl_match_blocks(temps)
+                        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.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))
-                pass
-            finally:
-                # l2_log.debug(code, "m鍊煎奖鍝嶅洜瀛愶細{}", l2_trade_factor.L2TradeFactorUtil.factors_to_string(code))
-                pass
-            return True
+                    async_log_util.exception(logger_l2_error, e)
+                    l2_log.debug(code, "鎵ц涔板叆寮傚父:{}", str(e))
+                    pass
+                finally:
+                    # l2_log.debug(code, "m鍊煎奖鍝嶅洜瀛愶細{}", l2_trade_factor.L2TradeFactorUtil.factors_to_string(code))
+                    pass
+                return True
 
     # 鏄惁鍙互鍙栨秷
     @classmethod
@@ -1335,6 +1354,8 @@
                 order_begin_pos.mode = OrderBeginPosInfo.MODE_ACTIVE
                 order_begin_pos.sell_info = sell_info
                 fast_msg = sell_info
+                # 鐢ㄤ簡淇″彿灏卞繀椤绘竻闄ゆ帀鍘熸湁淇″彿
+                place_order_single_data_manager.L2TradeSingleDataManager.clear_data(code)
 
             # if not has_single:
             #     # 绗簩姝ワ細璁$畻闂數涓嬪崟淇″彿
@@ -1680,19 +1701,20 @@
             if code.find("60") == 0:
                 threshold_money = 0
             else:
-                for i in range(start_index - 1, -1, -1):
-                    val = total_datas[i]["val"]
-                    if tool.compare_time(val["time"], refer_sell_data[0]) < 0:
-                        # 灏嗘湰s鐨勮绠椾笂鍘�
-                        break
-                    if L2DataUtil.is_sell(val):
-                        threshold_money += val["num"] * int(float(val["price"]) * 100)
-                    elif L2DataUtil.is_sell_cancel(val):
-                        threshold_money -= val["num"] * int(float(val["price"]) * 100)
-                    elif L2DataUtil.is_buy(val):
-                        # 鍒ゆ柇浠锋牸锛堝ぇ浜庡崠1锛� 琚拱鍚冩帀
-                        if round(float(val["price"]), 2) - sell_1_price >= 0:
-                            threshold_money -= val["num"] * int(float(val["price"]) * 100)
+                pass
+                # for i in range(start_index - 1, -1, -1):
+                #     val = total_datas[i]["val"]
+                #     if tool.compare_time(val["time"], refer_sell_data[0]) < 0:
+                #         # 灏嗘湰s鐨勮绠椾笂鍘�
+                #         break
+                #     if L2DataUtil.is_sell(val):
+                #         threshold_money += val["num"] * int(float(val["price"]) * 100)
+                #     elif L2DataUtil.is_sell_cancel(val):
+                #         threshold_money -= val["num"] * int(float(val["price"]) * 100)
+                #     elif L2DataUtil.is_buy(val):
+                #         # 鍒ゆ柇浠锋牸锛堝ぇ浜庡崠1锛� 琚拱鍚冩帀
+                #         if round(float(val["price"]), 2) - sell_1_price >= 0:
+                #             threshold_money -= val["num"] * int(float(val["price"]) * 100)
             # 绗簩姝ワ細璁$畻璧峰淇″彿
             second_930 = 9 * 3600 + 30 * 60 + 0
             total_datas = local_today_datas.get(code)
@@ -1712,6 +1734,14 @@
                     if _val["num"] * float(_val["price"]) < 5000:
                         continue
                     if last_index is None or (total_datas[last_index]["val"]["time"] == total_datas[i]["val"]["time"]):
+                        single = place_order_single_data_manager.L2TradeSingleDataManager.get_valid_trade_single(code,
+                                                                                                                 tool.to_time_with_ms(
+                                                                                                                     _val[
+                                                                                                                         'time'],
+                                                                                                                     _val[
+                                                                                                                         'tms']))
+                        if not single:
+                            continue
                         if start is None:
                             start = i
                         last_index = i
@@ -2103,6 +2133,11 @@
         trigger_buy = True
         # 闂撮殧鏈�澶ф椂闂翠负3s
         max_space_time_ms = 3 * 1000
+        if code.find("00") == 0 and threshold_money > 0:
+            # 娣辫瘉闈炴澘涓婃斁閲�
+            max_space_time_ms = 1 * 1000
+            threshold_num = 0
+
         # 涓嶄笅鍗曠殑淇℃伅
         not_buy_msg = ""
         max_buy_num_set = set(max_num_set)
@@ -2121,12 +2156,12 @@
                     for ii in range(buy_single_index + 1, compute_end_index + 1):
                         if total_datas[buy_single_index]["val"]["time"] != total_datas[ii]["val"]["time"]:
                             return None, buy_nums, buy_count, ii, threshold_money, max_buy_num_set, f"銆恵i}銆戜俊鍙蜂笉杩炵画锛屽泭鎷椂闂�-{max_space_time_ms}ms"
-            if L2DataUtil.is_sell(_val):
-                threshold_money += _val["num"] * int(float(_val["price"]) * 100)
-                threshold_num = round(threshold_money / (limit_up_price * 100))
-            elif L2DataUtil.is_sell_cancel(_val):
-                threshold_money -= _val["num"] * int(float(_val["price"]) * 100)
-                threshold_num = round(threshold_money / (limit_up_price * 100))
+            # if L2DataUtil.is_sell(_val):
+            #     threshold_money += _val["num"] * int(float(_val["price"]) * 100)
+            #     threshold_num = round(threshold_money / (limit_up_price * 100))
+            # elif L2DataUtil.is_sell_cancel(_val):
+            #     threshold_money -= _val["num"] * int(float(_val["price"]) * 100)
+            #     threshold_num = round(threshold_money / (limit_up_price * 100))
             # 娑ㄥ仠涔�
             elif L2DataUtil.is_limit_up_price_buy(_val):
                 if l2_data_util.is_big_money(_val):
@@ -2186,6 +2221,9 @@
             if threshold_money <= 0:
                 # 鏉夸笂涓嬪崟闇�瑕佸畨鍏ㄧ瑪鏁�3绗�
                 safe_count = 3
+            elif code.find("00") == 0:
+                # 娣辫瘉闈炴澘涓婃斁閲�
+                safe_count = 2
 
             if buy_count < safe_count:
                 not_buy_msg = f"銆恵i}銆戝畨鍏ㄧ瑪鏁颁笉瓒筹紝{buy_count}/{safe_count}"

--
Gitblit v1.8.0