Administrator
2022-09-30 394e24aaba9b28c6427444d47aab6505c735fb7e
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
from __future__ import print_function, absolute_import
 
import datetime
import json
import time as t
import schedule
 
import gm.api as gmapi
 
import big_money_num_manager
import code_volumn_manager
import data_process
import global_util
import gpcode_manager
import threading
 
import server
import tool
 
import redis_manager
import authority
import decimal
from l2_code_operate import L2CodeOperate
from log import logger_juejin_tick, logger_system
 
redisManager = redis_manager.RedisManager()
 
 
# 设置账户信息
def setAccountInfo(accountId, strategyId, token):
    redis = redisManager.getRedis()
    redis.set("juejin-account-id", accountId)
    redis.set("juejin-strategy-id", strategyId)
    redis.set("juejin-token", token)
 
 
def getAccountInfo():
    redis = redisManager.getRedis()
    account_id = redis.get("juejin-account-id")
    strategy_id = redis.get("juejin-strategy-id")
    token = redis.get("juejin-token")
    return account_id, strategy_id, token
 
 
def init_data():
    # 载入行业股票代码
    global_util.load_industry()
    # 载入代码自由流通市值
    global_util.load_zyltgb()
    # 载入量
    global_util.load_volumn()
 
 
# 每日初始化
def everyday_init():
    codes = gpcode_manager.get_gp_list()
    logger_system.info("每日初始化")
 
    # 今日实时涨停
    global_util.add_limit_up_codes([], True)
    # 主要获取收盘价
    get_latest_info(None)
    # 获取60天最大量与昨日量
    global_util.today_volumn.clear()
    global_util.max60_volumn.clear()
    global_util.yesterday_volumn.clear()
    volumn_dict = get_volumns(codes)
    for key in volumn_dict:
        code_volumn_manager.set_histry_volumn(key, volumn_dict[key][0], volumn_dict[key][1])
    # 清除大单数据
    global_util.big_money_num.clear()
    # 初始化大单数据
    for code in codes:
        big_money_num_manager.add_num(code, 0)
        big_money_num_manager.expire(code)
    # 清除涨停时间
    global_util.limit_up_time.clear()
    init_data()
    # 初始化同花顺主站
    l2_clients = data_process.getValidL2Clients()
    for client in l2_clients:
        server.repair_ths_main_site(client)
 
 
 
 
 
def __run_schedule():
    while True:
        schedule.run_pending()
 
 
def init(context):
    # gmapi.subscribe(symbols="SZSE.002529", frequency="1d", count=30)
 
    # 订阅浦发银行, bar频率为一天和一分钟
    # 订阅订阅多个频率的数据,可多次调用subscribe
    # 获取需要监听的股票
    init_data()
    logger_system.info("掘金初始化")
    schedule.every().day.at("09:15:00").do(everyday_init)
    t1 = threading.Thread(target=lambda: __run_schedule())
    # 后台运行
    t1.setDaemon(True)
    t1.start()
 
    # 多个时间点获取收盘价
    gmapi.schedule(schedule_func=get_latest_info, date_rule='1d', time_rule='08:30:00')
    gmapi.schedule(schedule_func=get_latest_info, date_rule='1d', time_rule='08:50:00')
    gmapi.schedule(schedule_func=get_latest_info, date_rule='1d', time_rule='09:28:00')
    gmapi.schedule(schedule_func=get_current_info, date_rule='1d', time_rule='09:25:00')
    gmapi.schedule(schedule_func=get_current_info, date_rule='1d', time_rule='09:29:00')
    re_subscribe_tick()
    # re_subscribe_bar()
 
    # 初始化内容
    clients = authority.get_l2_clients()
    for client in clients:
        for i in range(0, 8):
            gpcode_manager.init_listen_code_by_pos(client, i)
 
 
def get_latest_info(context):
    # 初始化内容
    clients = authority.get_l2_clients()
    for c in clients:
        for i in range(0, 8):
            gpcode_manager.init_listen_code_by_pos(int(c), i)
    codes = gpcode_manager.get_gp_list();
    result = JueJinManager.get_gp_latest_info(codes);
    for item in result:
        sec_level = item['sec_level']
        symbol = item['symbol']
        symbol = symbol.split(".")[1]
        pre_close = tool.to_price(decimal.Decimal(str(item['pre_close'])))
        if sec_level == 1:
            if symbol in codes:
                gpcode_manager.set_price_pre(symbol, pre_close)
        else:
            gpcode_manager.rm_gp(symbol)
 
 
# 获取最新的信息
def get_current_info():
    data = gpcode_manager.get_gp_list();
    results = JueJinManager.get_gp_current_info(data);
    logger_juejin_tick.debug("定时获取:{}", results)
    for result in results:
        price = result["price"]
        symbol = result['symbol']
        # 保存最新价
        symbol = symbol.split(".")[1]
        accpt_price(symbol, price)
 
 
# 设置收盘价
def re_set_price_pre(code):
    codes = [code]
    re_set_price_pres(codes)
 
 
def re_set_price_pres(codes):
    result = JueJinManager.get_gp_latest_info(codes);
    for item in result:
        symbol = item['symbol']
        symbol = symbol.split(".")[1]
        pre_close = tool.to_price(decimal.Decimal(str(item['pre_close'])))
        gpcode_manager.set_price_pre(symbol, pre_close)
 
 
__prices_now = {}
 
 
def on_tick(context, tick):
    if global_util.TEST:
        return
    # print(tick["created_at"])
    relative_timestamp = t.time() % (24 * 60 * 60) + 8 * 60 * 60
    # 9点20-15:05接受数据
    start1 = 60 * 60 * 9 + 31 * 60
    end1 = 60 * 60 * 11 + 35 * 60
    start2 = 60 * 60 * 12 + 50 * 60
    end2 = 60 * 60 * 15 + 5 * 60
    # TODO 测试
    if (start1 < relative_timestamp < end1 or start2 < relative_timestamp < end2) or global_util.TEST:
        symbol = tick['symbol']
        price = tick['price']
        # print(symbol,price)
        # 价格有变化的时候才发送操作
        # if symbol in __prices_now and __prices_now[symbol] == price:
        #     return
 
        # 保存最新价
        symbol = symbol.split(".")[1]
 
        accpt_price(symbol, price)
        __prices_now[symbol] = price
 
 
# 获取到现价
def accpt_price(code, price):
    gpcode_manager.set_price(code, price)
    # 获取收盘价
    pricePre = gpcode_manager.get_price_pre(code)
    if pricePre is not None:
        rate = round((price - pricePre) * 100 / pricePre, 1)
        if rate >= 7:
            logger_juejin_tick.info("{}-{}-{}", code, price, rate)
            if not gpcode_manager.is_listen(code) and not gpcode_manager.is_operate(
                    code) and not gpcode_manager.is_listen_full():
                L2CodeOperate.get_instance().add_operate(1, code, "现价变化")
            # 进入监控
        elif rate < 5:
            # 移除监控
            if gpcode_manager.is_listen(code) and not gpcode_manager.is_operate(code):
                L2CodeOperate.get_instance().add_operate(0, code, "现价变化")
 
 
# 获取到现价
def accpt_prices(prices):
    now_str = datetime.datetime.now().strftime("%H:%M:%S")
    now_strs = now_str.split(":")
    now_second = int(now_strs[0]) * 60 * 60 + int(now_strs[1]) * 60 + int(now_strs[2])
    start = 60 * 60 * 9 + 31 * 60
    if now_second > start:
        for d in prices:
            code, price = d["code"], float(d["price"])
            accpt_price(code, price)
    else:
        _code_list = []
        _delete_list = []
        for d in prices:
            code, price = d["code"], float(d["price"])
            gpcode_manager.set_price(code, price)
            # 获取收盘价
            pricePre = gpcode_manager.get_price_pre(code)
            if pricePre is not None:
                rate = round((price - pricePre) * 100 / pricePre, 1)
                if rate >= 0:
                    _code_list.append((rate, code))
                else:
                    _delete_list.append((rate, code))
        # 排序
        new_code_list = sorted(_code_list, key=lambda e: e.__getitem__(0), reverse=True)
        client_ids = data_process.getValidL2Clients()
        max_count = len(client_ids) * 8
        add_list = new_code_list[:max_count]
        _delete_list.extend(new_code_list[max_count:])
 
        add_code_list = []
        del_list = []
        for d in add_list:
            add_code_list.append(d[1])
 
        for d in _delete_list:
            del_list.append(d[1])
 
        for code in add_code_list:
            L2CodeOperate.get_instance().add_operate(1, code, "现价变化")
 
        for code in del_list:
            L2CodeOperate.get_instance().add_operate(0, code, "现价变化")
 
        print(add_code_list, del_list)
 
 
def on_bar(context, bars):
    print("on_bar", bars)
 
 
def re_subscribe_tick():
    gpcode_list = gpcode_manager.get_gp_list_with_prefix()
    codes_str = ",".join(gpcode_list)
    print("订阅:", codes_str)
    # TODO
    gmapi.subscribe(symbols=codes_str, frequency='tick', count=2, wait_group=False, wait_group_timeout='10s',
                    unsubscribe_previous=True)
 
 
def re_subscribe_bar():
    gpcode_list = gpcode_manager.get_gp_list_with_prefix()
    codes_str = ",".join(gpcode_list)
    print("订阅:", codes_str)
    gmapi.subscribe(symbols=codes_str, frequency='60s', count=1,
                    unsubscribe_previous=True)
 
 
def recieve_msg(pipe):
    while True:
        value = pipe.recv()
        print("跨进程通信:", value)
        jsonValue = json.loads(value)
        action = jsonValue["type"]
        if action == 'resub':
            re_subscribe_tick()
        elif action == 'accpt_price':
            try:
                datas = jsonValue["data"]
                for data in datas:
                    accpt_price(data["code"], float(data["price"]))
            except Exception as e:
                print(str(e))
 
 
class JueJinManager:
    def __init__(self, pipe):
        self.pipe = pipe
        # 开启线程接受数据
        t1 = threading.Thread(target=lambda: recieve_msg(pipe))
        t1.setDaemon(True)
        t1.start()
 
    @staticmethod
    def get_gp_latest_info(codes):
        account_id, s_id, token = getAccountInfo()
        symbols = gpcode_manager.get_gp_list_with_prefix(codes)
        gmapi.set_token(token)
        data = gmapi.get_instruments(symbols=",".join(symbols))
        print(data)
        return data
 
    @staticmethod
    def get_gp_current_info(codes):
        account_id, s_id, token = getAccountInfo()
        symbols = gpcode_manager.get_gp_list_with_prefix(codes)
        gmapi.set_token(token)
        data = gmapi.current(symbols=",".join(symbols))
        print(data)
        return data
 
    def start(self):
        account_id, s_id, token = getAccountInfo()
        gmapi.run(strategy_id=s_id,
                  filename='juejin.py',
                  # todo 回测模式
                  mode=gmapi.MODE_LIVE,
                  backtest_start_time='2022-08-18 09:25:00',
                  backtest_end_time='2022-08-18 10:30:00',
                  token=token)
 
    def stop(self):
        gmapi.stop()
 
 
def trade(code, volume):
    account_id, s_id, token = getAccountInfo()
    gmapi.set_token(token)
    gmapi.set_account_id(account_id)
    result = gmapi.order_volume(symbol=code, volume=volume, side=gmapi.OrderSide_Sell,
                                order_type=gmapi.OrderType_Market, position_effect=gmapi.PositionEffect_Close)
    print(result)
 
 
# 获取近90天的最大量与最近的量
def get_volumns(codes):
    end = datetime.datetime.now()
    # 获取近90天的历史数据
    cha = datetime.timedelta(days=90)
    start = end - cha
 
    account_id, s_id, token = getAccountInfo()
    gmapi.set_token(token)
    gmapi.set_account_id(account_id)
    results = gmapi.history(symbol=gpcode_manager.get_gp_list_with_prefix(codes), frequency="1d",
                            start_time="{:%Y-%m-%d}".format(start),
                            fields="symbol,volume,eob",
                            end_time="{:%Y-%m-%d}".format(end))
    _fresult = {}
 
    for result in results:
        code = result["symbol"].split(".")[1]
        volumn = int(result["volume"])
        day = "{:%Y-%m-%d}".format(result["eob"])
 
        if _fresult.get(code) is None:
            _fresult[code] = (volumn, volumn)
 
        if volumn > _fresult[code][0]:
            _fresult[code] = (volumn, _fresult[code][1])
        _fresult[code] = (_fresult[code][0], volumn)
    return _fresult
 
 
if __name__ == '__main__':
    pass