# 策略 Demo2:

import sys
import time
import json
import kungfu.yijinjing.time as kft
import kungfu.wingchun.utils as wc_utils
from kungfu.wingchun.constants import *
import pyyjj

#如果需要米筐数据,需要引入rqdatac
#import rqdatac as rq
#from rqdatac import*


source = Source.XTP
exchange = Exchange.SSE


def info_bar(context, bar) :
    context.log.info("Bar data, code: " + bar.code
        + ", bar data, trading_day: " + bar.trading_day
        + ", source_id: " + bar.source_id
        + ", instrument_id: " + bar.instrument_id
        + ", exchange_id: " + bar.exchange_id
        + ", start_time: " + str(bar.start_time)
        + ", end_time: " + str(bar.end_time)
        + ", time_interval: " + str(bar.time_interval)
        + ", period: " + bar.period
        + ", open: " + str(bar.open)
        + ", close: " + str(bar.close)
        + ", low: " + str(bar.low)
        + ", high: " + str(bar.high)
        + ", volume: " + str(bar.volume)
        + ", start_volume: " + str(bar.start_volume)
        + ", turnover: " + str(bar.turnover)
        + ", start_turnover: " + str(bar.start_turnover)
        )

def info_quote(context, quote) :
    context.log.info("Quote data, source_id: " + quote.source_id
    + ", trading_day: " + str(quote.trading_day)
    + ", data_time: " + str(quote.data_time)
    + ", instrument_id: " + str(quote.instrument_id)
    + ", exchange_id: " + str(quote.exchange_id)
    + ", instrument_type: " + str(quote.instrument_type)
    # + ", kungfu_time_flag: " + str(quote.kungfu_time_flag)
    + ", pre_close_price: " + str(quote.pre_close_price)
    + ", pre_settlement_price: " + str(quote.pre_settlement_price)
    + ", last_price: " + str(quote.last_price)
    + ", volume: " + str(quote.volume)
    + ", turnover: " + str(quote.turnover)
    + ", pre_open_interest: " + str(quote.pre_open_interest)
    + ", open_interest: " + str(quote.open_interest)
    + ", open_price: " + str(quote.open_price)
    + ", high_price: " + str(quote.high_price)
    + ", low_price: " + str(quote.low_price)
    + ", upper_limit_price: " + str(quote.upper_limit_price)
    + ", lower_limit_price: " + str(quote.lower_limit_price)
    + ", close_price: " + str(quote.close_price)
    + ", settlement_price: " + str(quote.settlement_price)
    + ", iopv: " + str(quote.iopv)
    + ", pre_iopv: " + str(quote.pre_iopv)
    + ", ticker_status: " + str(quote.ticker_status)
    )


def on_quote(context, quote) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called".format(func_name))
    info_quote(context, quote)


def info_data_frame(context, msg, data) :
    context.log.info(msg)
    for row in data.itertuples() :
        context.log.info("{} : {}".format(msg, row))

def info_numpy(context, msg, data) :
    context.log.info(msg)
    for row in data :
        context.log.info("{} : {}".format(msg, row))



#bar 分钟级别行情回调
def on_bar(context, bar) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called".format(func_name))

    info_bar(context, bar)



bar_callback_called_times = 0

def bar_callback(context, bar):
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called".format(func_name))

    info_bar(context, func_name, bar)


def test_sub_bar(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    codes1 = ["000001.SZ", "600000.SSE"]
    failed_codes = context.subscribe_bar(codes1, "3m", bar_callback)
    context.log.info("call {} done, failed_codes: {}".format(func_name, failed_codes))

    codes2 = ["000002.SZ", "600004.SSE"]
    failed_codes = context.subscribe_bar(codes2, "2m")
    context.log.info("call {} done, failed_codes: {}".format(func_name, failed_codes))


def on_indicator(context, indicator_type, indicator:dict) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called, indicator type: {}, indicator data: {}".format(func_name, indicator_type, json.dumps(indicator)))


def indicator_callback(context, indicator_type, indicator:dict) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called, indicator type: {}, indicator data: {}".format(func_name, indicator_type, json.dumps(indicator)))


def test_sub_indicator(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    codes1 = ["512160.SSE", "159631.SZ"]
    failed_codes  = context.subscribe_indicator("etf", codes1, indicator_callback)

    context.log.info("call {} done, failed_codes: {}".format(func_name, failed_codes))

    codes2 = ["561130.SSE", "159523.SZ"]
    failed_codes  = context.subscribe_indicator("etf", codes2)



def test_query_bar_today(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    ### 此处可以传两种形式的 code,即长码和短码,同时支持大小写
    codes = ["000002.SZ", "600000.SSE"]

    today_bar_data_map = context.query_bar_today(codes, "30m")

    for code, bars in today_bar_data_map.items() :
        context.log.info("{}, map code: {}".format(func_name, code))
        for bar in bars :
            info_bar(context, bar)

    context.log.info("{} end".format(func_name))


def today_bar_callback(context, today_bar_data_mp, query_id) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called, query_id: {}".format(func_name, query_id))
    for code, bars in today_bar_data_mp.items() :   ### 这里的 code 和调用 query_bar_today_async 时传入的 codes 相同
        context.log.info("map code: {}".format(code))
        for bar in bars :
            info_bar(context, bar)

def test_query_bar_today_async(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    ### 此处可以传两种形式的 code,即长码和短码,同时支持大小写
    codes = ["000002.SZ", "600000.SSE"]
    context.query_bar_today_async(codes, today_bar_callback, "60m", 22)

    context.log.info("{} end".format(func_name))

def test_query_market_data(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    params = {
        "code": "000001.SZ", # 证券代码  SZ:深证 SH:上海 String(必填)
        "start_date": "2024-01-12 10:00:00", # 开始日期 String(必填) 开始日期 格式yyyy-MM-dd hh:mm:ss
        "end_date": "2024-01-12 10:10:00" # 结束日期 String(必填) 结束日期 格式yyyy-MM-dd hh:mm:ss
    }

    quotes = context.query_market_data(params)

    if len(quotes) > 0 :
        for quote in quotes :
            info_quote(context, quote)


def query_market_data_callback(context, quotes, query_id) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called, query_id: {}".format(func_name, query_id))

    if len(quotes) > 0 :
        for quote in quotes :
            info_quote(context, quote)

def test_query_market_data_async(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    params = {
        "code": "000001.SZ", # 证券代码  SZ:深证 SH:上海 String(必填)
        "start_date": "2024-01-12 10:00:00", # 开始日期 String(必填) 开始日期 格式yyyy-MM-dd hh:mm:ss
        "end_date": "2024-01-12 10:10:00" # 结束日期 String(必填) 结束日期 格式yyyy-MM-dd hh:mm:ss
    }

    context.query_market_data_async(params, query_market_data_callback, 23)

def test_query_bar(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))
    params = {
        # "code": "", # String(必填) 证券代码  SZ:深证 SH:上海
        "instrument": "000002",
        "exchange_id": "SZE",
        "start_date": "2024-01-24 10:00:00", # String(必填) 开始日期
        "end_date": "2024-01-24 11:00:00", # String(必填) 结束日期
        "period": "15m", # #String(选填) 频次 仅支持1m 5m 15m 30m 60m 1d 1w 默认1d,(m代表分钟,d代表天,w代表周),注意:查询1d的则开始、截止时间需要将00:00:00包住,查询1w的则开始、截止时间需要将周五的00:00:00包住
        "adjust_type": "pre" # String(选填) 复权方式 none:不复权 pre:前复权 post:后复权 默认前复权
    }

    bars = context.query_bar(params)

    if len(bars) > 0 :
        for bar in bars :
            info_bar(context, bar)

def query_bar_callback(context, bar_list, query_id) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called, query_id: {}".format(func_name, query_id))

    if len(bar_list) > 0 :
        for bar in bar_list :
            info_bar(context, bar)

def test_query_bar_async(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))
    params = {
        "code": "000001.SZ", # String(必填) 证券代码  SZ:深证 SH:上海
        "instrument_id" : "600000",
        "exchange_id" : "SSE",
        "start_date": "2024-01-23 10:00:00", # String(必填) 开始日期
        "end_date": "2024-01-24 10:00:00", # String(必填) 结束日期
        "period": "60m", # String(选填) 频次 仅支持1m 15m 30m 60m 1d 1w 默认1d
        "adjust_type": "pre" # String(选填) 复权方式 none:不复权 pre:前复权 post:后复权 默认前复权
    }

    bars = context.query_bar_async(params, query_bar_callback, 24)

    context.log.info("call query_bar_async done")



# 查询历史 bar 数据
def test_query_data(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    out_format = OutFormat.List
    method = "bar" # String(必填)

    ### 以下参数中如果传了 code 则可以不传 instrument_id 和 exchange_id,如果传了 instrument_id 和 exchange_id,如果同时传了,则使用 code
    params = {
        "code": "000001.SZ", # 证券代码  SZ:深证 SH:上海
        "instrument_id" : "600000",
        "exchange_id" : "SSE",
        "start_date": "2013-01-04", # String(必填) 开始日期
        "end_date": "2013-01-08", # String(必填) 结束日期
        "period": "1d", # String(选填) 频次 仅支持1m 15m 30m 60m 1d 1w 默认1d
        "adjust_type": "pre" # String(选填) 复权方式 none:不复权 pre:前复权 post:后复权 默认前复权
    }

    result = context.query_data(method, params, out_format)

    ###
    ''' result 的类型为 dict,查询结果 result 如下所示, data 的格式由 out_format 指定
    {
        "code": 200
        "msg": ""
        "data" : [
            {},   ### 此处的格式由 out_format 指定
            {},
            .....
        ]
    }
    '''

    code = result.get("code")
    msg = result.get("msg")

    context.log.info("code: " + str(code) + ", msg: " + msg)    ### 当 code 为 200 时表示请求正常,其他值均为异常

    if code == 200 :
        for bar in result.get("data") :
            context.log.info("{} : {}".format(func_name, json.dumps(bar)))


    context.log.info("{} end".format(func_name))



def query_data_async_callback_list(context, result, query_id) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called, query_id: {}".format(func_name, query_id))

    code = result.get("code")
    msg = result.get("msg")

    context.log.info("code: " + str(code) + ", msg: " + msg)    ### 当 code 为 200 时表示请求正常,其他值均为异常

    context.log.info("{} called, data: {}".format(func_name, json.dumps(result.get("data"))))



def test_query_data_async(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    out_format = OutFormat.List
    method = "bar" # String(必填) method方法:固定值
    params = {
        "code": "000001.SZ", # String(必填) 证券代码  SZ:深证 SH:上海
        "start_date": "2013-01-04", # String(必填) 开始日期
        "end_date": "2013-01-08", # String(必填) 结束日期
        "period": "1d", # String(选填) 频次 仅支持1m 15m 30m 60m 1d 1w 默认1d
        "adjust_type": "pre" # String(选填) 复权方式 none:不复权 pre:前复权 post:后复权 默认前复权
    }
    context.query_data_async(method, params, query_data_async_callback_list, out_format, 25)



# 同步分页查询历史 bar 数据
def test_query_data_page(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    out_format = OutFormat.List
    page_size = 100
    current_page = 1
    method = "bar" # String(必填) method方法:固定值
    params = {
        "code": "000001.SZ", # String(必填) 证券代码  SZ:深证 SH:上海
        "start_date": "2013-01-04", # String(必填) 开始日期
        "end_date": "2014-01-04", # String(必填) 结束日期
        "period": "1d", # String(选填) 频次 仅支持1m 15m 30m 60m 1d 1w 默认1d
        "adjust_type": "pre", # String(选填) 复权方式 none:不复权 pre:前复权 post:后复权 默认前复权
        "page_size": page_size,
        "current_page": current_page
    }

    data_page_info = context.query_data_page(method, params, out_format)

    context.log.info("{}, currentPage: {}, totalPage: {}, pageSize: {}, totalCount: {}".format(func_name, data_page_info.currentPage, data_page_info.totalPage, data_page_info.pageSize, data_page_info.totalCount))

    code = data_page_info.data.get("code")
    msg = data_page_info.data.get("msg")

    context.log.info("data code: " + str(code) + ", msg: " + msg)

    if code == 200 :
        if (len(data_page_info.data.get("data")) > 0) :
            for bar in data_page_info.data.get("data") :
                context.log.info("{}, bar data: {}".format(func_name, json.dumps(bar)))
        else :
            context.log.info("{}, data is empty".format(func_name))

    context.log.info("{} end".format(func_name))


def query_data_page_async_callback_list(context, data_page_info, query_id) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} called, query_id:{}".format(func_name, query_id))
    context.log.info("{}, currentPage: {}, totalPage: {}, pageSize: {}, totalCount: {}".format(func_name, data_page_info.currentPage, data_page_info.totalPage, data_page_info.pageSize, data_page_info.totalCount))

    code = data_page_info.data.get("code")
    msg = data_page_info.data.get("msg")

    context.log.info("data code: " + str(code) + ", msg: " + msg)

    if code == 200 :
        if (len(data_page_info.data.get("data")) > 0) :
            for bar in data_page_info.data.get("data") :
                context.log.info("{}, bar data: {}".format(func_name, json.dumps(bar)))
        else :
            context.log.info("{}, data is empty".format(func_name))

    context.log.info("{} end".format(func_name))


def test_query_data_page_async(context) :
    func_name = sys._getframe().f_code.co_name
    context.log.info("{} start".format(func_name))

    page_size = 100
    current_page = 1

    out_format = OutFormat.List
    method = "bar" # String(必填) method方法:固定值
    params = {
        "code": "000001.SZ", # String(必填) 证券代码  SZ:深证 SH:上海
        "start_date": "2013-01-04", # String(必填) 开始日期
        "end_date": "2013-01-08", # String(必填) 结束日期
        "period": "1d", # String(选填) 频次 仅支持1m 15m 30m 60m 1d 1w 默认1d
        "adjust_type": "pre", # String(选填) 复权方式 none:不复权 pre:前复权 post:后复权 默认前复权
        "page_size": page_size,
        "current_page": current_page
    }
    context.query_data_page_async(method, params, query_data_page_async_callback_list, out_format, 345)


#启动前
def pre_start(context):
    context.log.info("pre_start called")
    context.send_msg("call send_msg")

#策略退出前,可在此做一些回收工作
def pre_stop(context):
    context.log.info("pre_stop called")
    context.log.info("strategy pre_stop.")

#退出后
def post_stop(context):
    context.log.info("post_stop called")
    pass



#启动后
def post_start(context):
    context.log.info("post_start called")

    test_query_bar_today(context)
    test_query_bar_today_async(context)

    test_query_bar(context)
    test_query_bar_async(context)

    test_query_market_data(context)
    test_query_market_data_async(context)

    test_query_data(context)
    test_query_data_async(context)


    test_query_data_page(context)
    test_query_data_page_async(context)

    test_sub_indicator(context)

    test_sub_bar(context)

    pass

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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456

备注:“策略 Demo2”,从 2.1.2 版本开始支持