-
Notifications
You must be signed in to change notification settings - Fork 118
/
agent.py
1816 lines (1674 loc) · 84.1 KB
/
agent.py
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#-*- coding:utf-8 -*-
import workdays
import time
import copy
import datetime
import logging
import bisect
import mysqlaccess
import order as order
import math
import os
import csv
import instrument
import pandas as pd
from base import *
from misc import *
import data_handler
import backtest
import pyktlib
import numpy as np
from eventType import *
from eventEngine import *
MAX_REALTIME_DIFF = 100
min_data_list = ['datetime', 'min_id', 'open', 'high','low', 'close', 'volume', 'openInterest']
day_data_list = ['date', 'open', 'high','low', 'close', 'volume', 'openInterest']
def get_tick_id(dt):
return ((dt.hour+6)%24)*100000+dt.minute*1000+dt.second*10+dt.microsecond/100000
def get_tick_num(dt):
return ((dt.hour+6)%24)*36000+dt.minute*600+dt.second*10+dt.microsecond/100000
def get_min_id(dt):
return ((dt.hour+6)%24)*100+dt.minute
def trading_hours(product, exch):
hrs = [(1500, 1615), (1630, 1730), (1930, 2100)]
if exch in ['SSE', 'SZE']:
hrs = [(1530, 1730), (1900, 2100)]
elif exch == 'CFFEX':
if product in ['IF', 'IH', 'IC']:
hrs = [(1530, 1730), (1900, 2100)]
else:
hrs = [(1515, 1730), (1900, 2115)]
else:
if product in night_session_markets:
night_idx = night_session_markets[product]
hrs = [night_trading_hrs[night_idx]] + hrs
return hrs
class TickData:
def __init__(self, instID='IF1412', high=0.0, low=0.0, price=0.0, volume=0, openInterest=0,
bidPrice1=0.0, bidVol1=0, askPrice1=0.0, askVol1=0,
up_limit = 0.0, down_limit = 0.0, timestamp=datetime.datetime.now()):
self.instID = instID
self.high = high
self.low = low
self.price = price
self.volume = volume
self.openInterest = openInterest
self.bidPrice1 = bidPrice1
self.bidVol1 = bidVol1
self.askPrice1 = askPrice1
self.askVol1 = askVol1
self.upLimit = up_limit
self.downLimit = down_limit
self.timestamp = timestamp
self.hour = timestamp.hour
self.min = timestamp.minute
self.sec = timestamp.second
self.msec = timestamp.microsecond/1000
self.tick_id = ((self.hour+6)%24)*100000+self.min*1000+self.sec*10+int(self.msec/100)
self.date = timestamp.date().strftime('%Y%m%d')
pass
class StockTick(TickData):
def __init__(self, instID='IF1412', high=0.0, low=0.0, price=0.0, open=0.0, close=0.0,
volume=0, openInterest=0, turnover=0, up_limit = 0.0, down_limit = 0.0,
timestamp=datetime.datetime.now(),
bidPrice1=0.0, bidVol1=0, askPrice1=0.0, askVol1=0,
bidPrice2=0.0, bidVol2=0, askPrice2=0.0, askVol2=0,
bidPrice3=0.0, bidVol3=0, askPrice3=0.0, askVol3=0,
bidPrice4=0.0, bidVol4=0, askPrice4=0.0, askVol4=0,
bidPrice5=0.0, bidVol5=0, askPrice5=0.0, askVol5=0):
TickData.__init__(self, instID, high, low, price, volume, openInterest,
bidPrice1, bidVol1, askPrice1, askVol1,
up_limit, down_limit, timestamp)
self.turnover = turnover
self.open = open
self.close = close
self.bidPrice2 = bidPrice2
self.bidVol2 = bidVol2
self.askPrice2 = askPrice2
self.askVol2 = askVol2
self.bidPrice3 = bidPrice3
self.bidVol3 = bidVol3
self.askPrice3 = askPrice3
self.askVol3 = askVol3
self.bidPrice4 = bidPrice4
self.bidVol4 = bidVol4
self.askPrice4 = askPrice4
self.askVol4 = askVol4
self.bidPrice5 = bidPrice5
self.bidVol5 = bidVol5
self.askPrice5 = askPrice5
self.askVol5 = askVol5
pass
class CTPMdMixin(object):
def OnRspError(self, info, RequestId, IsLast):
"""错误回报"""
event = Event(type=EVENT_LOG)
log = u'行情错误回报,错误代码:' + unicode(info.ErrorID) + u',' + u'错误信息:' + info.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.WARNING
self.eventEngine.put(event)
def OnFrontDisConnected(self, reason):
"""服务器断开"""
event = Event(type=EVENT_LOG)
event.dict['log'] = u'行情服务器连接断开'
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
def OnFrontConnected(self):
event = Event(type=EVENT_LOG)
event.dict['log'] = u'行情服务器连接成功'
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
self.user_login(self.broker_id, self.investor_id, self.passwd)
def user_login(self, broker_id, investor_id, passwd):
req = self.ApiStruct.ReqUserLogin(BrokerID=broker_id, UserID=investor_id, Password=passwd)
r=self.ReqUserLogin(req,self.agent.inc_request_id())
pass
def OnRspUserLogin(self, userlogin, info, rid, is_last):
event = Event(type=EVENT_LOG)
if info.ErrorID == 0:
log = u'行情服务器登陆成功'
else:
log = u'登陆回报,错误代码:' + unicode(info.ErrorID) + u',' + u'错误信息:' + info.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
if is_last and (info.ErrorID == 0):
trade_day_str = self.GetTradingDay()
trading_day = datetime.date.today()
if len(trade_day_str) > 0:
try:
trading_day = datetime.datetime.strptime(trade_day_str,'%Y%m%d').date()
except ValueError:
pass
self.subscribe_market_data(self.instruments)
if trading_day > self.agent.scur_day: #换日,重新设置volume
event = Event(type=EVENT_DAYSWITCH)
event.dict['log'] = u'换日: %s -> %s' % (self.agent.scur_day, trading_day)
event.dict['date'] = trading_day
self.eventEngine.put(event)
#self.agent.day_switch(trading_day)
def OnRtnDepthMarketData(self, dp):
try:
if dp.LastPrice > dp.UpperLimitPrice or dp.LastPrice < dp.LowerLimitPrice:
event = Event(type=EVENT_LOG)
event.dict['log'] = u'MD:error in market data - last price:%s,LastPrice=:%s' %(dp.InstrumentID,dp.LastPrice)
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
return
if (dp.AskPrice1 > dp.UpperLimitPrice and dp.BidPrice1 <= dp.LowerLimitPrice) or (dp.BidPrice1 >= dp.AskPrice1):
event = Event(type=EVENT_LOG)
event.dict['log'] = u'MD:error in market data - bid ask:%s,BidPrice=%s, AskPrice=%s' %(dp.InstrumentID,dp.BidPrice1,dp.AskPrice1)
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
return
timestr = str(dp.UpdateTime) + ' ' + str(dp.UpdateMillisec) + '000'
if len(dp.TradingDay.strip()) > 0:
timestr = str(dp.TradingDay) + ' ' + timestr
else:
timestr = str(self.last_day) + ' ' + timestr
timestamp = datetime.datetime.strptime(timestr, '%Y%m%d %H:%M:%S %f')
self.last_day = timestamp.year*10000+timestamp.month*100+timestamp.day
tick = self.market_data2tick(dp, timestamp)
event = Event(type=EVENT_MARKETDATA)
event.dict['data'] = tick
self.eventEngine.put(event)
finally:
pass
class CTPTraderQryMixin(object):
def query_instrument_marginrate(self, instrument_id):
req = self.ApiStruct.QryInstrumentMarginRate(BrokerID=self.broker_id,
InvestorID=self.investor_id,
InstrumentID=instrument_id,
HedgeFlag = self.ApiStruct.HF_Speculation
)
r = self.ReqQryInstrumentMarginRate(req,self.agent.inc_request_id())
return r
def query_instrument(self, instrument_id):
req = self.ApiStruct.QryInstrument(
InstrumentID=instrument_id,
)
r = self.ReqQryInstrument(req, self.agent.inc_request_id())
return r
def query_instruments_by_exch(self, exchange_id):
req = self.ApiStruct.QryInstrument(
ExchangeID=exchange_id,
)
r = self.ReqQryInstrument(req, self.agent.inc_request_id())
return r
def query_trading_account(self):
req = self.ApiStruct.QryTradingAccount(BrokerID=self.broker_id, InvestorID=self.investor_id)
r=self.ReqQryTradingAccount(req,self.agent.inc_request_id())
return r
def query_investor_position(self, instrument_id):
req = self.ApiStruct.QryInvestorPosition(BrokerID=self.broker_id, InvestorID=self.investor_id,InstrumentID=instrument_id)
r=self.ReqQryInvestorPosition(req,self.agent.inc_request_id())
return r
def query_investor_position_detail(self, instrument_id):
req = self.ApiStruct.QryInvestorPositionDetail(BrokerID=self.broker_id, InvestorID=self.investor_id, InstrumentID=instrument_id)
r=self.ReqQryInvestorPositionDetail(req, self.agent.inc_request_id())
return r
def query_order(self, startTime = '', endTime = ''):
req = self.ApiStruct.QryOrder(
BrokerID = self.broker_id,
InvestorID = self.investor_id,
InstrumentID ='',
ExchangeID = '', #交易所代码, char[9]
InsertTimeStart = startTime, #开始时间, char[9]
InsertTimeEnd = endTime, #结束时间, char[9]
)
r = self.ReqQryOrder(req, self.agent.inc_request_id())
return r
def query_trade( self, startTime = '', endTime = '' ):
req = self.ApiStruct.QryTrade(
BrokerID=self.broker_id,
InvestorID=self.investor_id,
InstrumentID='',
ExchangeID ='', #交易所代码, char[9]
TradeTimeStart = startTime, #开始时间, char[9]
TradeTimeEnd = endTime, #结束时间, char[9]
)
r = self.ReqQryTrade(req, self.agent.inc_request_id())
return r
def queryDepthMarketData(self, instrument):
req = self.ApiStruct.QryDepthMarketData(InstrumentID=instrument)
r=self.ReqQryDepthMarketData(req, self.agent.inc_request_id())
###交易操作
def send_order(self, iorder):
if not self.is_logged:
event = Event(type=EVENT_LOG)
event.dict['log'] = 'The trader is not logged, cannot send the order, so cancelling order ref = %s, sysid = %s' % (iorder.order_ref, iorder.sys_id)
event.dict['level'] = logging.WARNING
self.eventEngine.put(event)
iorder.on_cancel()
return False
if iorder.direction == ORDER_BUY:
direction = self.ApiStruct.D_Buy
else:
direction = self.ApiStruct.D_Sell
if iorder.price_type == OPT_MARKET_ORDER:
price_type = self.ApiStruct.OPT_AnyPrice
elif iorder.price_type == OPT_LIMIT_ORDER:
price_type = self.ApiStruct.OPT_LimitPrice
if iorder.action_type == OF_OPEN:
action_type = self.ApiStruct.OF_Open
elif iorder.action_type == OF_CLOSE:
action_type = self.ApiStruct.OF_Close
elif iorder.action_type == OF_CLOSE_TDAY:
action_type = self.ApiStruct.OF_CloseToday
elif iorder.action_type == OF_CLOSE_YDAY:
action_type = self.ApiStruct.OF_CloseYesterday
limit_price = iorder.limit_price
if self.name == 'LTS-TD':
limit_price = str(limit_price)
req = self.ApiStruct.InputOrder(
InstrumentID = iorder.instrument.name,
Direction = direction,
OrderRef = str(iorder.order_ref),
LimitPrice = limit_price, #LTS uses char, CTP uses double
VolumeTotalOriginal = iorder.volume,
OrderPriceType = price_type,
BrokerID = self.broker_id,
InvestorID = self.investor_id,
CombOffsetFlag = action_type, #开仓 5位字符,但是只用到第0位
CombHedgeFlag = self.ApiStruct.HF_Speculation, #投机 5位字符,但是只用到第0位
VolumeCondition = self.ApiStruct.VC_AV,
MinVolume = 1, #这个作用有点不确定,有的文档设成0了
ForceCloseReason = self.ApiStruct.FCC_NotForceClose,
IsAutoSuspend = 1,
UserForceClose = 0,
TimeCondition = self.ApiStruct.TC_GFD,
)
event = Event(type=EVENT_LOG)
event.dict['log'] = u'下单: order_ref=%s, instrument=%s,开关=%s,方向=%s,数量=%s,价格=%s ->%s' % (iorder.order_ref, \
iorder.instrument.name,
'open' if iorder.action_type == OF_OPEN else 'close',
u'多' if iorder.direction==ORDER_BUY else u'空',
iorder.volume,
iorder.limit_price,
iorder.price_type)
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
r = self.ReqOrderInsert(req,self.agent.inc_request_id())
return r
def cancel_order(self, iorder):
inst = iorder.instrument
event = Event(type=EVENT_LOG)
event.dict['log'] = u'A_CC:取消命令: OrderRef=%s, OrderSysID=%s, exchange=%s, instID=%s, volume=%s, filled=%s, cancelled=%s' % (iorder.order_ref, \
iorder.sys_id, inst.exchange, inst.name, iorder.volume, iorder.filled_volume, iorder.cancelled_volume)
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
if len(iorder.sys_id) >0:
exch = inst.exchange
req = self.ApiStruct.InputOrderAction(
InstrumentID = inst.name,
BrokerID = self.broker_id,
InvestorID = self.investor_id,
ExchangeID = exch,
OrderSysID = iorder.sys_id,
ActionFlag = self.ApiStruct.AF_Delete,
)
else:
event = Event(type=EVENT_LOG)
event.dict['log'] = 'order=%s has no OrderSysID, using Order_ref to cancel' % (iorder.order_ref)
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
req = self.ApiStruct.InputOrderAction(
InstrumentID = inst.name,
OrderRef = str(iorder.order_ref),
BrokerID = self.broker_id,
InvestorID = self.investor_id,
FrontID = self.front_id,
SessionID = self.session_id,
ActionFlag = self.ApiStruct.AF_Delete,
)
r = self.ReqOrderAction(req,self.agent.inc_request_id())
return r
class CTPTraderRspMixin(object):
def isRspSuccess(self, RspInfo):
return RspInfo == None or RspInfo.ErrorID == 0
def login(self):
self.user_login(self.broker_id, self.investor_id, self.passwd)
##交易初始化
def OnFrontConnected(self):
'''
当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。
'''
"""服务器连接"""
event = Event(type=EVENT_LOG)
event.dict['log'] = u'交易服务器连接成功'
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
self.login()
def OnFrontDisconnected(self, nReason):
"""服务器断开"""
self.is_logged = False
event = Event(type=EVENT_LOG)
event.dict['log'] = u'交易服务器连接断开'
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
event2 = Event(type=EVENT_TDDISCONNECTED)
event2.dict['log'] = u'交易服务器连接断开'
self.eventEngine.put(event2)
def user_login(self, broker_id, investor_id, passwd):
req = self.ApiStruct.ReqUserLogin(BrokerID=broker_id, UserID=investor_id, Password=passwd)
r=self.ReqUserLogin(req,self.agent.inc_request_id())
def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
event = Event(type=EVENT_LOG)
if pRspInfo.ErrorID == 0:
log = u'交易服务器登陆成功'
else:
log = u'登陆回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
if pRspInfo.ErrorID == 0:
self.is_logged = True
self.front_id = pRspUserLogin.FrontID
self.session_id = pRspUserLogin.SessionID
else:
self.is_logged = False
time.sleep(30)
self.login()
def OnRspUserLogout(self, pUserLogout, pRspInfo, nRequestID, bIsLast):
'''登出请求响应'''
event = Event(type=EVENT_LOG)
if pRspInfo.ErrorID == 0:
log = u'交易服务器登出成功'
else:
log = u'登陆回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
self.is_logged = False
def resp_common(self,rsp_info,bIsLast,name='默认'):
event = Event(type=EVENT_LOG)
if not self.isRspSuccess(rsp_info):
log = u'TD:%s失败' % name
val = -1
elif bIsLast and self.isRspSuccess(rsp_info):
log = u'TD:%s成功' % name
val = 1
else:
log = u'TD:%s结果: 等待数据接收完全...' % name
val = 0
event.dict['log'] = log
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
return val
def OnRspQryDepthMarketData(self, depth_market_data, pRspInfo, nRequestID, bIsLast):
pass
###交易准备
def OnRspQryInstrumentMarginRate(self, pInstMarginRate, pRspInfo, nRequestID, bIsLast):
'''
保证金率回报。返回的必然是绝对值
'''
if self.isRspSuccess(pRspInfo):
event = Event(type = EVENT_MARGINRATE)
event.dict['data'] = copy.copy(pInstMarginRate)
event.dict['error'] = copy.copy(pRspInfo)
event.dict['isLast'] = bIsLast
self.eventEngine.put(event)
def OnRspQryInstrument(self, pInstrument, pRspInfo, nRequestID, bIsLast):
'''
获得合约数量乘数.
这里的保证金率应该是和期货公司无关,所以不能使用
'''
if pInstrument.InstrumentID not in self.agent.instruments:
return
if self.isRspSuccess(pRspInfo):
event = Event(type = EVENT_INSTRUMENT)
event.dict['data'] = copy.copy(pInstrument)
event.dict['error'] = copy.copy(pRspInfo)
event.dict['isLast'] = bIsLast
self.eventEngine.put(event)
else:
event = Event(type=EVENT_LOG)
log = u'合约投资者回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
def OnRspQryTradingAccount(self, pTradingAccount, pRspInfo, nRequestID, bIsLast):
"""资金账户查询回报"""
if self.isRspSuccess(pRspInfo):
event = Event(type = EVENT_ACCOUNT)
event.dict['data'] = copy.copy(pTradingAccount)
event.dict['error'] = copy.copy(pRspInfo)
event.dict['isLast'] = bIsLast
self.eventEngine.put(event)
else:
event = Event(type=EVENT_LOG)
log = u'账户查询回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
def OnRspQryInvestor(self, pInvestorPosition, pRspInfo, nRequestID, bIsLast):
"""投资者查询回报"""
if self.isRspSuccess(pRspInfo):
event = Event(type=EVENT_INVESTOR)
event.dict['data'] = copy.copy(pInvestorPosition)
event.dict['isLast'] = bIsLast
self.eventEngine.put(event)
else:
event = Event(type=EVENT_LOG)
log = u'合约投资者回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
def OnRspQryInvestorPosition(self, pInvestorPosition, pRspInfo, nRequestID, bIsLast):
"""持仓查询回报"""
if self.isRspSuccess(pRspInfo):
event = Event(type=EVENT_POSITION)
event.dict['data'] = copy.copy(pInvestorPosition)
event.dict['isLast'] = bIsLast
self.eventEngine.put(event)
else:
event = Event(type=EVENT_LOG)
log = u'持仓查询回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
def OnRspQryInvestorPositionDetail(self, pInvestorPositionDetail, pRspInfo, nRequestID, bIsLast):
'''请求查询投资者持仓明细响应'''
pass
def OnRspError(self, info, RequestId, IsLast):
"""错误回报"""
event = Event(type=EVENT_LOG)
log = u'交易错误回报,错误代码:' + unicode(info.ErrorID) + u',' + u'错误信息:' + info.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.INFO
self.eventEngine.put(event)
def OnRspQryOrder(self, porder, pRspInfo, nRequestID, bIsLast):
'''请求查询报单响应'''
#print porder, pRspInfo, bIsLast
if self.isRspSuccess(pRspInfo):
event = Event(type=EVENT_QRYORDER)
event.dict['data'] = copy.copy(porder)
event.dict['isLast'] = bIsLast
self.eventEngine.put(event)
else:
event = Event(type=EVENT_LOG)
log = u'交易错误回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
def OnRspQryTrade(self, ptrade, pRspInfo, nRequestID, bIsLast):
'''请求查询成交响应'''
#print ptrade, pRspInfo, bIsLast
if self.isRspSuccess(pRspInfo):
event = Event(type=EVENT_QRYTRADE)
event.dict['data'] = copy.copy(ptrade)
event.dict['isLast'] = bIsLast
self.eventEngine.put(event)
else:
event = Event(type=EVENT_LOG)
log = u'交易错误回报,错误代码:' + unicode(info.ErrorID) + u',' + u'错误信息:' + info.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.DEBUG
self.eventEngine.put(event)
def OnRspOrderInsert(self, pInputOrder, pRspInfo, nRequestID, bIsLast):
'''
报单未通过参数校验,被CTP拒绝
正常情况后不应该出现
'''
event = Event(type=EVENT_LOG)
log = u' 发单错误回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.WARNING
self.eventEngine.put(event)
event2 = Event(type=EVENT_ERRORDERINSERT)
event2.dict['data'] = copy.copy(pInputOrder)
event2.dict['error'] = copy.copy(pRspInfo)
self.eventEngine.put(event2)
def OnErrRtnOrderInsert(self, pInputOrder, pRspInfo):
"""发单错误回报(交易所)"""
event = Event(type=EVENT_LOG)
log = u'发单错误回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.WARNING
self.eventEngine.put(event)
event2 = Event(type=EVENT_ERRORDERINSERT)
event2.dict['data'] = copy.copy(pInputOrder)
event2.dict['error'] = copy.copy(pRspInfo)
self.eventEngine.put(event2)
def OnRtnOrder(self, porder):
''' 报单通知
CTP、交易所接受报单(CTP接受的已经被过滤)
Agent中不区分,所得信息只用于撤单,暂时只处理撤单的回报.
'''
# 常规报单事件
event1 = Event(type=EVENT_ORDER)
event1.dict['data'] = copy.copy(porder)
self.eventEngine.put(event1)
# 特定合约行情事件
event2 = Event(type=(EVENT_ORDER_ORDERREF+porder.OrderRef))
event2.dict['data'] = copy.copy(porder)
self.eventEngine.put(event2)
def OnRtnTrade(self, ptrade):
'''成交回报
#TODO: 必须考虑出现平仓信号时,position还没完全成交的情况在OnTrade中进行position的细致处理
#TODO: 必须处理策略分类持仓汇总和持仓总数不匹配时的问题
'''
# 常规成交事件
event1 = Event(type=EVENT_TRADE)
event1.dict['data'] = copy.copy(ptrade)
self.eventEngine.put(event1)
# 特定合约成交事件
event2 = Event(type=(EVENT_TRADE_CONTRACT+ptrade.InstrumentID))
event2.dict['data'] = copy.copy(ptrade)
self.eventEngine.put(event2)
def OnRspOrderAction(self, pInputOrderAction, pRspInfo, nRequestID, bIsLast):
'''
ctp撤单校验错误
'''
event = Event(type=EVENT_LOG)
log = u'撤单错误回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.WARNING
self.eventEngine.put(event)
event2 = Event(type=EVENT_ERRORDERCANCEL)
event2.dict['data'] = copy.copy(pInputOrderAction)
event2.dict['error'] = copy.copy(pRspInfo)
self.eventEngine.put(event2)
def OnErrRtnOrderAction(self, pOrderAction, pRspInfo):
"""撤单错误回报(交易所)"""
event = Event(type=EVENT_LOG)
log = u'撤单错误回报,错误代码:' + unicode(pRspInfo.ErrorID) + u',' + u'错误信息:' + pRspInfo.ErrorMsg.decode('gbk')
event.dict['log'] = log
event.dict['level'] = logging.WARNING
self.eventEngine.put(event)
event2 = Event(type=EVENT_ERRORDERCANCEL)
event2.dict['data'] = copy.copy(pOrderAction)
event2.dict['error'] = copy.copy(pRspInfo)
self.eventEngine.put(event2)
class Agent(object):
def __init__(self, name, trader, cuser, instruments, strategies = [], tday=datetime.date.today(), config = {}):
'''
trader为交易对象
tday为当前日,为0则为当日
'''
self.tick_id = 0
self.timer_count = 0
self.request_id = 1
folder = 'C:\\dev\\src\\ktlib\\pythonctp\\pyctp\\'
if 'folder' in config:
folder = config['folder']
daily_data_days = 60
if 'daily_data_days' in config:
daily_data_days = config['daily_data_days']
min_data_days = 5
if 'min_data_days' in config:
min_data_days = config['min_data_days']
live_trading = False
if 'live_trading' in config:
live_trading = config['live_trading']
self.logger = logging.getLogger('ctp.agent')
self.mdapis = []
self.trader = trader
self.name = name
self.folder = folder + self.name + os.path.sep
self.cuser = cuser
self.initialized = False
self.scur_day = tday
#保存分钟数据标志
self.save_flag = False #默认不保存
self.live_trading = live_trading
self.tick_db_table = 'fut_tick'
self.min_db_table = 'fut_min'
self.daily_db_table = 'fut_daily'
self.eod_flag = False
# market data
self.daily_data_days = daily_data_days
self.min_data_days = min_data_days
self.instruments = {}
self.tick_data = {}
self.day_data = {}
self.min_data = {}
self.cur_min = {}
self.cur_day = {}
self.positions= {}
self.qry_pos = {}
self.day_data_func = {}
self.min_data_func = {}
self.inst2strat = {}
self.add_instruments(instruments, self.scur_day)
self.strategies = {}
self.strat_list = []
for strat in strategies:
self.add_strategy(strat)
###交易
self.ref2order = {} #orderref==>order
self.ref2trade = {}
#self.queued_orders = [] #因为保证金原因等待发出的指令(合约、策略族、基准价、基准时间(到秒))
#当前资金/持仓
self.available = 0 #可用资金
self.locked_margin = 0
self.used_margin = 0
self.margin_cap = 1500000
self.pnl_total = 0.0
self.curr_capital = 1000000.0
self.prev_capital = 1000000.0
self.ctp_orders = []
self.eventEngine = EventEngine(1)
self.eventEngine.register(EVENT_LOG, self.log_handler)
self.eventEngine.register(EVENT_MARKETDATA, self.rtn_tick)
self.eventEngine.register(EVENT_TIMER, self.check_qry_commands)
self.eventEngine.register(EVENT_DAYSWITCH, self.day_switch)
self.cancel_protect_period = 200
self.market_order_tick_multiple = 5
self.order_stats = dict([(inst,{'submitted': 0, 'cancelled':0, 'failed': 0, 'status': True }) for inst in self.instruments])
self.total_submitted = 0
self.total_cancelled = 0
self.total_submitted_limit = 1000
self.submitted_limit_per_inst = 100
self.failed_order_limit = 200
##查询命令队列
self.qry_commands = [] #每个元素为查询命令,用于初始化时查询相关数据
self.init_init() #init中的init,用于子类的处理
#结算单
self.isSettlementInfoConfirmed = False #结算单未确认
def set_capital_limit(self, margin_cap):
self.margin_cap = margin_cap
def log_handler(self, event):
lvl = event.dict['level']
self.logger.log(lvl, event.dict['log'])
def td_disconnected(self, event):
pass
def time_scheduler(self, event):
if self.timer_count % 1800:
if self.tick_id >= 2100000-10:
min_id = get_min_id(datetime.datetime.now())
if (min_id >= 2116) and (self.eod_flag == False):
self.qry_commands.append(self.run_eod)
def add_instruments(self, names, tday):
add_names = [ name for name in names if name not in self.instruments]
for name in add_names:
if name.isdigit():
if len(name) == 8:
self.instruments[name] = instrument.StockOptionInst(name)
else:
self.instruments[name] = instrument.Stock(name)
else:
if len(name) > 10:
self.instruments[name] = instrument.FutOptionInst(name)
else:
self.instruments[name] = instrument.Future(name)
self.instruments[name].update_param(tday)
self.tick_data[name] = []
self.day_data[name] = pd.DataFrame(columns=['open', 'high','low','close','volume','openInterest'])
self.min_data[name] = {1: pd.DataFrame(columns=['open', 'high','low','close','volume','openInterest','min_id'])}
self.cur_min[name] = dict([(item, 0) for item in min_data_list])
self.cur_day[name] = dict([(item, 0) for item in day_data_list])
self.positions[name] = order.Position(self.instruments[name])
self.day_data_func[name] = []
self.min_data_func[name] = {}
self.qry_pos[name] = {'tday': [0, 0], 'yday': [0, 0]}
self.cur_min[name]['datetime'] = datetime.datetime.fromordinal(self.scur_day.toordinal())
self.cur_day[name]['date'] = tday
if name not in self.inst2strat:
self.inst2strat[name] = {}
def add_strategy(self, strat):
self.add_instruments(strat.instIDs, self.scur_day)
for instID in strat.instIDs:
self.inst2strat[instID][strat.name] = []
self.strategies[strat.name] = strat
self.strat_list.append(strat.name)
strat.agent = self
strat.reset()
def initialize(self, event):
'''
初始化,如保证金率,账户资金等
'''
self.isSettlementInfoConfirmed = True
if not self.initialized:
for inst in self.instruments:
self.instruments[inst].update_param(self.scur_day)
#self.resume()
self.qry_commands = []
self.qry_commands.append(self.fetch_trading_account)
self.qry_commands.append(self.fetch_investor_position)
self.qry_commands.append(self.fetch_order)
self.qry_commands.append(self.fetch_trade)
def register_data_func(self, inst, freq, fobj):
if inst not in self.day_data_func:
self.day_data_func[inst] = []
self.min_data_func[inst] = {}
if 'd' in freq:
for func in self.day_data_func[inst]:
if fobj.name == func.name:
return False
self.day_data_func[inst].append(fobj)
return True
else:
mins = int(freq[:-1])
if mins not in self.min_data_func[inst]:
self.min_data_func[inst][mins] = []
for func in self.min_data_func[inst][mins]:
if fobj.name == func.name:
return False
if fobj != None:
self.min_data_func[inst][mins].append(fobj)
return True
def prepare_data_env(self, mid_day = True):
if self.daily_data_days > 0 or mid_day:
self.logger.debug('Updating historical daily data for %s' % self.scur_day.strftime('%Y-%m-%d'))
daily_start = workdays.workday(self.scur_day, -self.daily_data_days, CHN_Holidays)
daily_end = self.scur_day
for inst in self.instruments:
if (self.instruments[inst].ptype == instrument.ProductType.Option):
continue
self.day_data[inst] = mysqlaccess.load_daily_data_to_df('fut_daily', inst, daily_start, daily_end)
df = self.day_data[inst]
if len(df) > 0:
self.instruments[inst].price = df['close'][-1]
self.instruments[inst].last_update = 0
self.instruments[inst].prev_close = df['close'][-1]
for fobj in self.day_data_func[inst]:
ts = fobj.sfunc(df)
df[ts.name]= pd.Series(ts, index=df.index)
if self.min_data_days > 0 or mid_day:
self.logger.debug('Updating historical min data for %s' % self.scur_day.strftime('%Y-%m-%d'))
d_start = workdays.workday(self.scur_day, -self.min_data_days, CHN_Holidays)
d_end = self.scur_day
for inst in self.instruments:
if (self.instruments[inst].ptype == instrument.ProductType.Option):
continue
min_start = int(self.instruments[inst].start_tick_id/1000)
min_end = int(self.instruments[inst].last_tick_id/1000)+1
#print "loading inst = %s" % inst
mindata = mysqlaccess.load_min_data_to_df('fut_min', inst, d_start, d_end, minid_start=min_start, minid_end=min_end)
mindata = backtest.cleanup_mindata(mindata, self.instruments[inst].product)
self.min_data[inst][1] = mindata
if len(mindata)>0:
min_date = mindata.index[-1].date()
if (len(self.day_data[inst].index)==0) or (min_date > self.day_data[inst].index[-1]):
ddf = data_handler.conv_ohlc_freq(mindata, 'd')
self.cur_day[inst]['open'] = float(ddf.open[-1])
self.cur_day[inst]['close'] = float(ddf.close[-1])
self.cur_day[inst]['high'] = float(ddf.high[-1])
self.cur_day[inst]['low'] = float(ddf.low[-1])
self.cur_day[inst]['volume'] = int(ddf.volume[-1])
self.cur_day[inst]['openInterest'] = int(ddf.openInterest[-1])
self.cur_min[inst]['datetime'] = pd.datetime(*mindata.index[-1].timetuple()[0:-3])
self.cur_min[inst]['open'] = float(mindata.ix[-1,'open'])
self.cur_min[inst]['close'] = float(mindata.ix[-1,'close'])
self.cur_min[inst]['high'] = float(mindata.ix[-1,'high'])
self.cur_min[inst]['low'] = float(mindata.ix[-1,'low'])
self.cur_min[inst]['volume'] = self.cur_day[inst]['volume']
self.cur_min[inst]['openInterest'] = self.cur_day[inst]['openInterest']
self.cur_min[inst]['min_id'] = int(mindata.ix[-1,'min_id'])
self.instruments[inst].price = float(mindata.ix[-1,'close'])
self.instruments[inst].last_update = 0
self.logger.debug('inst=%s tick data loaded for date=%s' % (inst, min_date))
for m in self.min_data_func[inst]:
if m != 1:
self.min_data[inst][m] = data_handler.conv_ohlc_freq(self.min_data[inst][1], str(m)+'min')
df = self.min_data[inst][m]
for fobj in self.min_data_func[inst][m]:
ts = fobj.sfunc(df)
df[ts.name]= pd.Series(ts, index=df.index)
return
def resume(self):
if self.initialized:
return
self.logger.debug('Prepare market data for %s' % self.scur_day.strftime('%y%m%d'))
self.prepare_data_env(mid_day = True)
self.get_eod_positions()
self.logger.debug('Prepare trade environment for %s' % self.scur_day.strftime('%y%m%d'))
file_prefix = self.folder
self.ref2order = order.load_order_list(self.scur_day, file_prefix, self.positions)
keys = self.ref2order.keys()
if len(keys) > 1:
keys.sort()
for key in keys:
iorder = self.ref2order[key]
if len(iorder.conditionals)>0:
self.ref2order[key].conditionals = dict([(self.ref2order[o_id], iorder.conditionals[o_id])
for o_id in iorder.conditionals])
self.ref2trade = order.load_trade_list(self.scur_day, file_prefix)
for trade_id in self.ref2trade:
etrade = self.ref2trade[trade_id]
orderdict = etrade.order_dict
for inst in orderdict:
etrade.order_dict[inst] = [ self.ref2order[order_ref] for order_ref in orderdict[inst] ]
etrade.update()
for strat_name in self.strat_list:
strat = self.strategies[strat_name]
strat.initialize()
strat_trades = [etrade for etrade in self.ref2trade.values() if (etrade.strategy == strat.name) \
and (etrade.status != order.ETradeStatus.StratConfirm)]
for trade in strat_trades:
strat.add_live_trades(trade)
for inst in self.positions:
self.positions[inst].re_calc()
self.calc_margin()
self.initialized = True
self.eventEngine.start()
def check_qry_commands(self, event):
self.timer_count += 1
if len(self.qry_commands)>0:
self.qry_commands[0]()
del self.qry_commands[0]
self.logger.debug(u'查询命令序列长度:%s' % (len(self.qry_commands),))
def check_price_limit(self, inst, num_tick):
inst_obj = self.instruments[inst]
tick_base = inst_obj.tick_base
if (inst_obj.ask_price1 >= inst_obj.up_limit - num_tick * tick_base) or (inst_obj.bid_price1 <= inst_obj.down_limit + num_tick * tick_base):
return True
else:
return False
def get_eod_positions(self):
file_prefix = self.folder
pos_date = self.scur_day
logfile = file_prefix + 'EOD_Pos_' + pos_date.strftime('%y%m%d')+'.csv'
if not os.path.isfile(logfile):
pos_date = workdays.workday(pos_date, -1, CHN_Holidays)
logfile = file_prefix + 'EOD_Pos_' + pos_date.strftime('%y%m%d')+'.csv'
if not os.path.isfile(logfile):
return False
else:
self.eod_flag = True
self.logger.debug('Starting; getting EOD position for %s' % pos_date.strftime('%y%m%d'))
with open(logfile, 'rb') as f:
reader = csv.reader(f)
for idx, row in enumerate(reader):
if row[0] == 'capital':
self.prev_capital = float(row[1])
self.logger.debug('getting prev EOD capital = %s' % row[1])
elif row[0] == 'pos':
inst = row[1]
if inst in self.positions:
self.positions[inst].pos_yday.long = int(row[2])
self.positions[inst].pos_yday.short = int(row[3])
self.instruments[inst].prev_close = float(row[4])
self.logger.debug('getting prev EOD pos = %s: long=%s, short=%s, price=%s' % (row[1], row[2], row[3], row[4]))
return True
def save_eod_positions(self):
file_prefix = self.folder
logfile = file_prefix + 'EOD_Pos_' + self.scur_day.strftime('%y%m%d')+'.csv'
self.logger.info('EOD process: saving EOD position for %s' % self.scur_day.strftime('%y%m%d'))
if os.path.isfile(logfile):
self.logger.info('EOD position file for %s already exists' % self.scur_day.strftime('%y%m%d'))
return False
else:
with open(logfile,'wb') as log_file:
file_writer = csv.writer(log_file, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL);
for inst in self.positions:
pos = self.positions[inst]
pos.re_calc()
self.calc_margin()
file_writer.writerow(['capital', self.curr_capital])
for inst in self.positions:
price = self.instruments[inst].price
pos = self.positions[inst]
file_writer.writerow(['pos', inst, pos.curr_pos.long, pos.curr_pos.short, price])
return True
def calc_margin(self):
locked_margin = 0
used_margin = 0
yday_pnl = 0
tday_pnl = 0
for instID in self.instruments:
inst = self.instruments[instID]
pos = self.positions[instID]
under_price = 0.0
if (inst.ptype == instrument.ProductType.Option):