Administrator
2025-07-01 bccc14e6d890cefb5309c904a6413bea1270ff03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import json
import logging
import os
import threading
 
import constant
 
from api.outside_api_command_manager import ActionCallback
from code_attribute import gpcode_manager
from huaxin_client import l1_subscript_codes_manager
from huaxin_client.client_network import SendResponseSkManager
from strategy import strategy_params_settings, env_info, strategy_manager
from strategy.env_info import RealTimeEnvInfo
from strategy.strategy_manager import PlateWhiteListManager
from strategy.strategy_params_settings import StrategyParamsSettingsManager, StrategyParamsSettings
from strategy.strategy_variable_factory import DataLoader
from third_data.history_k_data_manager import TradeDateManager
from third_data.kpl_block_manager import KPLCodeJXBlocksManager
from trade import trade_record_log_util
from trade.trade_manager import TradeStateManager
from utils import socket_util, middle_api_protocol, tool
 
OPERRATE_SET = 1  # 设置
OPERRATE_DELETE = 2  # 删除
OPERRATE_GET = 3  # 获取
OPERRATE_ADD = 4  # 新增
 
 
class MyAPICallback(ActionCallback):
 
    @classmethod
    def __send_response(cls, data_bytes):
        sk = SendResponseSkManager.create_send_response_sk(addr=middle_api_protocol.SERVER_HOST,
                                                           port=middle_api_protocol.SERVER_PORT)
        try:
            data_bytes = socket_util.load_header(data_bytes)
            sk.sendall(data_bytes)
            result, header_str = socket_util.recv_data(sk)
            result = json.loads(result)
            if result["code"] != 0:
                raise Exception(result['msg'])
        finally:
            sk.close()
 
    def send_response(self, data, _client_id, _request_id):
        data_bytes = json.dumps({"type": "response", "data": data, "client_id": _client_id,
                                 "request_id": _request_id}).encode('utf-8')
        for i in range(3):
            try:
                self.__send_response(data_bytes)
                # print("发送数据成功")
                break
            except Exception as e1:
                logging.exception(e1)
 
    def __on_get_settings(self):
        """
        获取交易参数
        @return:
        """
        result = strategy_params_settings.StrategyParamsSettingsManager().get_settings().to_json_str()
        result = json.loads(result)
        result["trade_state"] = 1 if TradeStateManager().is_can_buy_cache() else 0
 
        return {"code": 0, "data": result}
 
    def __on_set_settings(self, data):
        """
        设置交易参数
        @return:
        """
        settings = strategy_params_settings.StrategyParamsSettingsManager().get_settings()
        settings_vars = vars(settings)
        for k in data:
            if k == "trade_state":
                if data[k]:
                    TradeStateManager().open_buy()
                else:
                    TradeStateManager().close_buy()
                continue
            if k not in settings_vars:
                # 没有在属性里面
                continue
            settings.__setattr__(k, data[k])
        strategy_params_settings.StrategyParamsSettingsManager().set_settings(settings)
        # 同步参数设置
        return {"code": 0, "data": {}}
 
    def __on_get_env(self, need_hsitory_data):
        """
        获取环境信息
        @param need_hsitory_data: 是否需要历史数据
        @return:
        """
        fdata = {}
        # 实时数据
        fdata["real_time_data"] = RealTimeEnvInfo().to_dict()
        # 历史数据
        fdata["history_data"] = {}
        print("获取环境", os.getpid())
        if need_hsitory_data:
            if tool.get_now_time_str() < '16:00:00':
                # 如果在16:00之前采用当前日期
                day = tool.get_now_date_str()
            else:
                # 如果在16:00之后采用下一个交易日
                day = TradeDateManager().get_next_trade_day(tool.get_now_date_str())
            fdata["history_data"][
                "leading_limit_up_block_codes_count"] = env_info.get_leading_limit_up_block_codes_count(
                day)
 
            if tool.get_now_time_str() < '16:00:00':
                # 如果在16:00之前采用当前日期
                day = TradeDateManager().get_previous_trade_day(tool.get_now_date_str())
            else:
                # 如果在16:00之后采用下一个交易日
                day = tool.get_now_date_str()
            fdata["history_data"]["k_bars_count"] = env_info.get_history_k_bars(day)
 
            day = tool.get_now_date_str()
            fdata["history_data"]["kpl_code_jx_blocks_count"] = env_info.get_kpl_code_jx_blocks(day)
 
        return {"code": 0, "data": fdata, "msg": "测试结果"}
 
    def __on_update_leading_limit_up_datas(self):
        """
        更新领涨代码信息
        @return:
        """
 
        def update():
            plates = __DataLoader.get_limit_up_reasons_with_plate_code()
            for p in plates:
                print(p)
                __DataLoader.load_plate_codes(p[0], p[1])
 
        if tool.get_now_time_str() < '16:00:00':
            # 如果在16:00之前采用当前日期
            day = tool.get_now_date_str()
        else:
            # 如果在16:00之后采用下一个交易日
            day = TradeDateManager().get_next_trade_day(tool.get_now_date_str())
        __DataLoader = DataLoader(day)
        threading.Thread(target=lambda: update(), daemon=True).start()
        return {"code": 0}
 
    def __on_update_kpl_code_jx_blocks_datas(self):
        """
        更新开盘啦精选板块数据
        @return:
        """
 
        def update():
            codes = set()
            codes_sh, codes_sz = l1_subscript_codes_manager.get_codes()
            codes |= set([x.decode() for x in codes_sh])
            codes |= set([x.decode() for x in codes_sz])
            KPLCodeJXBlocksManager(day, codes).start_download_blocks()
            # 如果在16:00之前采用当前日期
 
        day = tool.get_now_date_str()
        threading.Thread(target=lambda: update(), daemon=True).start()
        return {"code": 0}
 
    def __on_init_data(self):
        try:
            strategy_manager.low_suction_strtegy.load_data()
            return {"code": 0}
        except Exception as e:
            logging.exception(e)
            return {"code": 1, "msg": str(e)}
 
    def __on_plate_white_list(self, data):
        operate = data["operate"]
        if operate == OPERRATE_GET:
            plates = PlateWhiteListManager().get_plates()
            return {"code": 0, "data": list(plates)}
        elif operate == OPERRATE_ADD:
            plate = data["plate"]
            PlateWhiteListManager().add_plate(plate)
            return {"code": 0}
        elif operate == OPERRATE_DELETE:
            plate = data["plate"]
            PlateWhiteListManager().remove_plate(plate)
            return {"code": 0}
 
    def OnCommonRequest(self, client_id, request_id, data):
        ctype = data["ctype"]
        result_json = {}
        if ctype == "get_settings":
            result_json = self.__on_get_settings()
        elif ctype == 'set_settings':
            del data["ctype"]
            result_json = self.__on_set_settings(data)
        elif ctype == 'get_env':
            # 获取环境数据
            result_json = self.__on_get_env(data.get("history"))
        elif ctype == 'update_leading_limit_up_datas':
            # 更新领涨数据
            result_json = self.__on_update_leading_limit_up_datas()
        elif ctype == 'update_kpl_code_jx_blocks_datas':
            # 更新开盘啦精选数据
            result_json = self.__on_update_kpl_code_jx_blocks_datas()
        elif ctype == 'init_datas':
            # 初始化数据
            result_json = self.__on_init_data()
        elif ctype == 'get_place_order_records':
            # 获取下单记录
            datas = trade_record_log_util.get_trade_records(trade_record_log_util.TYPE_PLACE_ORDER)
            for data in datas:
                data[3]["code_name"] = gpcode_manager.CodesNameManager().get_code_name(data[3]["code"])
            result_json = {"code": 0, "data": datas}
        elif ctype == 'get_can_buy_plates':
            # 获取可以买的板块
            settings: StrategyParamsSettings = StrategyParamsSettingsManager().get_settings()
            try:
                current_limit_up_plate_codes = strategy_manager.low_suction_strtegy.current_limit_up_plate_codes
                plates = [plate for plate, codes in current_limit_up_plate_codes.items() if
                          len(codes) >= settings.limit_up_count_of_new_plate]
            except:
                plates = []
            result_json = {"code": 0, "data": plates}
 
 
 
        elif ctype == 'plate_white_list':
            result_json = self.__on_plate_white_list(data)
        self.send_response(result_json, client_id, request_id)