admin
2024-12-16 ec012b7d2b915db24cd8b23f723bf18dfe75b7d6
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
"""
网络代理管理器
"""
# 本地看盘网络代理
import decimal
import json
import time
from urllib.parse import parse_qs, urlparse
 
import setting
import trade_gui
from convertible_bonds.main import JueJinUtil
from juejin_core import JueJinApi
from kpl import kpl_util, kpl_api
from kpl.kpl_data_manager import KPLLimitUpDataManager
from utils import tool, xgb_api
 
 
class LocalKanPanNetworkDelegate:
    # 保存代码涨幅
    __code_limit_rate_dict = {}
 
    # HTTP代理请求
    @classmethod
    def http_delegate_request(cls, url):
        if url.startswith("/kpl/get_limit_up_list"):
            return cls.__get_limit_up_list(url)
 
        elif url.startswith("/kpl/get_market_data"):
            return cls.__get_market_data(url)
 
        elif url.startswith("/kpl/get_plate_codes"):
            return cls.__get_plate_codes(url)
 
        elif url.startswith("/get_last_trade_day_reasons"):
            return cls.__get_last_trade_day_reasons(url)
 
        elif url.startswith("/get_xgb_limit_up_reasons"):
            return cls.__get_xgb_limit_up_reasons(url)
 
        elif url.startswith("/get_kpl_market_feelings"):
            return cls.__get_kpl_market_feelings()
        elif url.startswith("/get_cb_list"):
            # 获取可转债的列表
            return cls.get_cb_list()
        elif url.startswith("/buy_by_ths"):
            # 获取可转债的列表
            return cls.buy_by_ths(url)
        return None, False
 
    @classmethod
    def __get_limit_up_list(cls, url):
        ps_dict = dict([(k, v[0]) for k, v in parse_qs(urlparse(url).query).items()])
        day = ps_dict.get("day")
        if day is None:
            day = tool.get_now_date_str()
        # (代码, 名称, 首次涨停时间, 最近涨停时间, 几板, 涨停原因, 板块, 实际流通, 主力净额, 涨停原因代码, 涨停原因代码数量)
        records = KPLLimitUpDataManager().get_limit_up_history_datas(day)
        currents = KPLLimitUpDataManager().get_limit_up_current_datas(day)
        current_codes = [d[0] for d in currents]
        fresult = []
        # 计算涨停时间排序
        record_reason_dict = {}
        current_reason_dict = {}
        for r in records:
            if r[5] not in record_reason_dict:
                record_reason_dict[r[5]] = []
            record_reason_dict[r[5]].append(r)
        for r in currents:
            if r[5] not in current_reason_dict:
                current_reason_dict[r[5]] = []
            current_reason_dict[r[5]].append(r)
 
        for k in record_reason_dict:
            record_reason_dict[k].sort(key=lambda x: x[2])
 
        for r in records:
            if r[0] in current_codes:
                limit_up_state = 1
            else:
                limit_up_state = 2
            rank = 0
            for i in range(len(record_reason_dict[r[5]])):
                if record_reason_dict[r[5]][i][0] == r[0]:
                    rank = i
            # (代码, 名称, 涨停状态(0 - 无状态 1-涨停 2-炸板), 龙几, 首板, 分值, 涨停时间, 原因, 相同原因代码数量, 自由流通, 涨停原因是否变化,涨停原因的流入净额,下单简介)
            fresult.append((r[0], r[1], limit_up_state, f"龙{rank + 1}", r[4], 0,
                            tool.time_format(int(r[2])), r[5], r[10], tool.money_desc(r[7]),
                            '', '', ''))
 
        # (板块名称,涨停代码数量,炸板数量,涨停时间)
        limit_up_reason_statistic_info = [(k, len(record_reason_dict[k]), len(record_reason_dict[k]) - len(
            current_reason_dict.get(k) if k in current_reason_dict else []),
                                           record_reason_dict[k][0][5]) for k in record_reason_dict]
        limit_up_reason_statistic_info.sort(key=lambda x: x[1] - x[2])
        limit_up_reason_statistic_info.reverse()
        result = json.dumps({"code": 0, "data": {"limit_up_count": len(currents),
                                                 "open_limit_up_count": len(records) - len(currents),
                                                 "limit_up_reason_statistic": limit_up_reason_statistic_info,
                                                 "limit_up_codes": fresult}})
        return result, True
 
    @classmethod
    def __get_market_data(cls, url):
        ps_dict = dict([(k, v[0]) for k, v in parse_qs(urlparse(url).query).items()])
        type_ = int(ps_dict['type'])
        result = []
        if type_ == 0:
            # 行业,主力净额倒序
            result = kpl_api.getMarketIndustryRealRankingInfo(True)
            result = kpl_util.parseMarketIndustry(result)
        elif type_ == 1:
            # 行业,主力净额顺序
            result = kpl_api.getMarketIndustryRealRankingInfo(False)
            result = kpl_util.parseMarketIndustry(result)
        elif type_ == 2:
            # 精选,主力净额倒序
            result = []
            for p in range(2):
                result_ = kpl_api.getMarketJingXuanRealRankingInfo(p + 1, True)
                result_ = kpl_util.parseMarketJingXuan(result_)
                result.extend(result_)
        elif type_ == 3:
            # 精选,主力净额顺序
            result = []
            for p in range(2):
                result_ = kpl_api.getMarketJingXuanRealRankingInfo(p + 1, False)
                result_ = kpl_util.parseMarketJingXuan(result_)
                result.extend(result_)
        fresult = []
        forbidden_plates = []
        for d in result:
            d = list(d)
            d.append(1 if d[1] in forbidden_plates else 0)
            fresult.append(d)
        response_data = json.dumps({"code": 0, "data": fresult})
        return response_data, True
 
    @classmethod
    def __get_plate_codes(cls, url):
        ps_dict = dict([(k, v[0]) for k, v in parse_qs(urlparse(url).query).items()])
        day = ps_dict.get("day")
        plate = ps_dict.get("plate")
        if not day:
            return None, False
        records = KPLLimitUpDataManager().get_limit_up_history_datas(day)
        currents = KPLLimitUpDataManager().get_limit_up_current_datas(day)
        rs = []
        for r in records:
            if r[5] != plate and plate not in r[6].split('、'):
                continue
            rs.append(r)
        current_codes = set()
        for r in currents:
            current_codes.add(r[0])
        rs.sort(key=lambda x: x[2])
 
        # 代码,名称,涨停时间,是否炸板,是否想买,是否已经下过单
        results = [(
            x[0], x[1], time.strftime("%H:%M:%S", time.localtime(x[2])), 0 if x[0] in current_codes else 1, 0, 0,
            x[4], f" {round(x[7] / 100000000, 1)}亿", 1 if x[5] == plate else 0) for x in rs]
        response_data = json.dumps({"code": 0, "data": results})
        return response_data, True
 
    @classmethod
    def get_codes_limit_rate(cls, codes):
        return cls.__get_codes_limit_rate(codes)
 
    # 获取昨日收盘价
    __pre_close_cache = {}
 
    @classmethod
    def __get_codes_limit_rate(cls, codes):
        latest_info_codes = set()
        for code in codes:
            if code not in cls.__pre_close_cache:
                latest_info_codes.add(code)
        if latest_info_codes:
            datas = JueJinApi.get_gp_latest_info(latest_info_codes, fields="sec_id,pre_close")
            for data in datas:
                code = data["sec_id"]
                pre_close = data['pre_close']
                cls.__pre_close_cache[code] = pre_close
 
        current_info = JueJinApi.get_gp_current_info(codes, fields="symbol,price")
        now_prices = [(c["symbol"].split(".")[1], c["price"]) for c in current_info]
        f_results = []
        for data in now_prices:
            code = data[0]
            price = data[1]
            pre_price = float(cls.__pre_close_cache.get(code))
            rate = round((price - pre_price) * 100 / pre_price, 2)
            f_results.append((code, rate))
        f_results.sort(key=lambda tup: tup[1])
        f_results.reverse()
        return f_results
 
    @classmethod
    def __get_limit_rate_list(cls, codes):
        if not codes:
            return []
        need_request_codes = set()
        if tool.trade_time_sub(tool.get_now_time_str(), "09:30:00") < 0:
            need_request_codes |= set(codes)
        else:
            now_time = time.time()
            for c in codes:
                if c not in cls.__code_limit_rate_dict:
                    need_request_codes.add(c)
                elif now_time - cls.__code_limit_rate_dict[c][1] > 60:
                    need_request_codes.add(c)
        if need_request_codes:
            _limit_rate_list = cls.__get_codes_limit_rate(list(need_request_codes))
            for d in _limit_rate_list:
                cls.__code_limit_rate_dict[d[0]] = (d[1], time.time())
        return [(c_, cls.__code_limit_rate_dict[c_][0]) for c_ in codes]
 
    @classmethod
    def __get_last_trade_day_reasons(cls, url):
        # 获取 昨日涨停数据
        ps_dict = dict([(k, v[0]) for k, v in parse_qs(urlparse(url).query).items()])
        code = ps_dict["code"]
        # 获取昨日涨停数据
        day = JueJinApi.get_previous_trading_date_cache(tool.get_now_date_str())
        # (代码, 名称, 首次涨停时间, 最近涨停时间, 几板, 涨停原因, 板块, 实际流通, 主力净额, 涨停原因代码, 涨停原因代码数量)
        limit_up_records = KPLLimitUpDataManager().get_limit_up_history_datas_cache(day)
        if not limit_up_records:
            limit_up_records = []
        reasons = []
        for d in limit_up_records:
            if d[0] == code:
                reasons.append(d)
        # 获取代码的原因
        if reasons:
            reasons = list(reasons)
            reasons.sort(key=lambda x: x[9])
            reason = reasons[-1][5]
            # 获取涨停数据
            datas = KPLLimitUpDataManager().get_limit_up_current_datas_cache(day)
            # (代码,名称,首次涨停时间,最近涨停时间,几板,涨停原因,板块,实际流通,主力净额,涨停原因代码,涨停原因代码数量)
            yesterday_result_list = []
            percent_rate = 0
            if datas:
                yesterday_codes = set()
                for d in datas:
                    if d[5] == reason:
                        yesterday_codes.add(d[0])
                # 获取涨幅
                limit_rate_list = cls.__get_limit_rate_list(yesterday_codes)
                limit_rate_dict = {}
                if limit_rate_list:
                    total_rate = 0
                    for d in limit_rate_list:
                        limit_rate_dict[d[0]] = d[1]
                        total_rate += d[1]
                    percent_rate = round(total_rate / len(limit_rate_list), 2)
 
                for d in datas:
                    if d[5] == reason:
                        yesterday_codes.add(d[0])
                        if d[0] != code:
                            # (代码,名称, 涨幅)
                            yesterday_result_list.append((d[0], d[1], limit_rate_dict.get(d[0])))
 
            current_limit_up_list = KPLLimitUpDataManager().get_limit_up_current_datas()
            current_result_list = []
            if current_limit_up_list:
                for c in current_limit_up_list:
                    if c[5] == reason and c[0] != code:
                        current_result_list.append((c[0], c[1]))
            response_data = json.dumps({"code": 0, "data": {"reason": reason, "reason_rate": percent_rate,
                                                            "data": {"yesterday": yesterday_result_list,
                                                                     "current": current_result_list}}})
        else:
            response_data = json.dumps({"code": 1, "msg": "昨日未涨停"})
 
        return response_data, True
 
    @classmethod
    def __get_xgb_limit_up_reasons(cls, url):
        # 获取 昨日涨停数据
        ps_dict = dict([(k, v[0]) for k, v in parse_qs(urlparse(url).query).items()])
        code = ps_dict["code"]
        reasons = xgb_api.get_code_limit_up_reasons(code)
        if reasons:
            response_data = json.dumps(
                {"code": 0, "data": {"reasons": reasons[0], "description": reasons[1], "blocks": reasons[2],
                                     "zylt": f"{reasons[3]}亿"}})
        else:
            response_data = json.dumps({"code": 1, "msg": "尚未获取到涨停原因"})
 
        return response_data, True
 
    @classmethod
    def __get_kpl_market_feelings(cls):
        market_feelings = kpl_api.getMarketFelling()
        market_strong = kpl_api.getMarketStrong()
        ps = [('涨停', market_feelings['ZT'], 'red')]
        ps.append(('>%7', int(market_feelings['8']) + int(market_feelings['9']) + int(
            market_feelings['10']), 'red'))
        ps.append(('7~5%', int(market_feelings['6']) + int(market_feelings['7']), 'red'))
        ps.append(('5~2%', int(market_feelings['3']) + int(market_feelings['4']) + int(market_feelings['5']), 'red'))
        ps.append(('2~0%', int(market_feelings['2']) + int(market_feelings['1']), 'red'))
        ps.append(('平', int(market_feelings['0']), 'gray'))
        ps.append(('0~2%', int(market_feelings['-1']) + int(market_feelings['-2']), 'green'))
        ps.append(
            ('2~5%', int(market_feelings['-3']) + int(market_feelings['-4']) + int(market_feelings['-5']), 'green'))
        ps.append(('5~7%', int(market_feelings['-6']) + int(market_feelings['-7']), 'green'))
        ps.append(
            ('7%<', int(market_feelings['-8']) + int(market_feelings['-9']) + int(market_feelings['-10']), 'green'))
        ps.append(('跌停', market_feelings['DT'], 'green'))
        fdata = {"strong": market_strong, "map": ps, "SJZT": market_feelings['SJZT'], "SJDT": market_feelings['SJDT'],
                 "SZJS": market_feelings['SZJS'], "XDJS": market_feelings['XDJS'], "sign": market_feelings['sign'],
                 "qscln": market_feelings['qscln'] // 10000, "q_zrcs": market_feelings['q_zrcs'] // 10000}
        # 获取市场情绪
        return json.dumps(
            {"code": 0, "data": fdata}), True
 
    __cb_codes_list = None  # 所有可转债数据
    __pre_price_dict = {}  # 昨日收盘价
 
    # 获取可转债的列表
    @classmethod
    def get_cb_list(cls):
        # 获取所有可转债列表
        if not cls.__cb_codes_list:
            cls.__cb_codes_list = JueJinUtil.get_all_convertible_bonds_codes()
            # 获取昨日收盘价
            symbols = [x[0][0] for x in cls.__cb_codes_list]
            symbols.extend([x[1] for x in cls.__cb_codes_list])
            # 获取现价
            results = JueJinApi.get_gp_latest_info(symbols, fields='symbol,pre_close')
            cls.__pre_price_dict = {x['symbol']: x['pre_close'] for x in results}
 
        # 获取涨停列表
        records = KPLLimitUpDataManager().get_limit_up_history_datas()
        currents = KPLLimitUpDataManager().get_limit_up_current_datas()
        current_codes = [d[0] for d in currents]
        record_codes = [d[0] for d in records]
        record_map = {}
        for r in records:
            record_map[r[0]] = r
        # 格式[([转债代码,转债名称, (现价,涨幅)],[正股代码,正股名称,(现价,涨幅)],正股涨停时间,是否炸板)]
        datas = []
        for b in cls.__cb_codes_list:
            code = b[1].split(".")[1]
            if code in record_codes:
                if record_map[code][4] != '首板':
                    continue
                datas.append(
                    [[b[0][0], b[0][1], None], [b[1], record_map[code][1], None], tool.time_format(record_map[code][2]),
                     code not in current_codes])
        # 获取所有的涨幅
        symbols = []
        for d in datas:
            symbols.append(d[0][0])
            symbols.append(d[1][0])
        # 获取当前
        current_infos = JueJinApi.get_gp_current_info(symbols, fields='symbol,price')
        rate_dict = {x['symbol']: (x['price'], round(
            (x['price'] - cls.__pre_price_dict[x['symbol']]) * 100 / cls.__pre_price_dict[x['symbol']], 2)) for x in
                     current_infos}
        for d in datas:
            d[0][2] = rate_dict[d[0][0]]
            d[1][2] = rate_dict[d[1][0]]
            d[0][0] = d[0][0].split('.')[1]
            d[1][0] = d[1][0].split('.')[1]
        datas.sort(key=lambda x: int(x[2].replace(":", "")), reverse=True)
 
        # 获取今日正股涨停的可转债列表
        return json.dumps(
            {"code": 0, "data": datas}), True
 
    @classmethod
    def buy_by_ths(cls, url):
        can_buy = setting.is_can_ths_buy()
        if can_buy:
            try:
                ps_dict = dict([(k, v[0]) for k, v in parse_qs(urlparse(url).query).items()])
                code = ps_dict["code"]
                trade_gui.start_buy(code)
                return json.dumps(
                    {"code": 0, "data": {}}), True
            except Exception as e:
                return json.dumps(
                    {"code": 1, "msg": str(e)}), True
        else:
            return json.dumps(
                {"code": 1, "msg": '同花顺不能买入'}), True
 
 
if __name__ == "__main__":
    codes = ["002523", "603095"]
    datas = LocalKanPanNetworkDelegate.get_cb_list()
    print(datas)