-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathaxob.py
1876 lines (1594 loc) · 90.6 KB
/
axob.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 -*-
'''
简单的行为模型,目标:
* 只针对单只股票
* 支持撮合和非撮合
* 支持深圳、上海
* 支持有涨跌停价、无涨跌停价
* 支持创业板价格笼子
* 支持股票和etf
* 尽量倾向便于FPGA硬件实现,梳理流程,不考虑面向C/C++实现
* 将遍历全市场以验证正确性,为提升验证效率,可能用C重写一遍
* 主要解决几个课题:
* 撮合是否必须保存每个价格档位的链表?
* 出快照的时机,是否必须等10ms超时?
* 位宽检查
* 访问次数
* save/load
'''
from enum import Enum
from tool.msg_util import axsbe_base, axsbe_exe, axsbe_order, axsbe_snap_stock, price_level, CYB_cage_upper, CYB_cage_lower
import tool.msg_util as msg_util
from tool.axsbe_base import SecurityIDSource_SSE, SecurityIDSource_SZSE, INSTRUMENT_TYPE
from copy import deepcopy
import logging
axob_logger = logging.getLogger(__name__)
#### 内部计算精度 ####
APPSEQ_BIT_SIZE = 32 # 序列号,34b,约40亿,因为不同channel的序列号各自独立,所以单channel整形就够
PRICE_BIT_SIZE = 25 # 价格,20b,33554431,股票:335544.31;基金:33554.431。(创业板上市首日有委托价格为¥188888.00的,若忽略这种特殊情况,则20b(10485.75)足够了)
QTY_BIT_SIZE = 30 # 数量,30b,(1,073,741,823),深圳2位小数,上海3位小数
LEVEL_QTY_BIT_SIZE = QTY_BIT_SIZE+7 # 价格档位上的数量位宽
TIMESTAMP_BIT_SIZE = 24 # 时戳精度 时-分-秒-10ms 最大15000000=24b
PRICE_INTER_STOCK_PRECISION = 100 # 股票价格精度:2位小数,(深圳原始数据4位,上海3位)
PRICE_INTER_FUND_PRECISION = 1000 # 基金价格精度:3位小数,(深圳原始数据4位,上海3位)
QTY_INTER_SZSE_PRECISION = 100 # 数量精度:深圳2位小数
QTY_INTER_SSE_PRECISION = 1000 # 数量精度:上海3位小数
SZSE_TICK_CUT = 1000000000 # 深交所时戳,日期以下精度
SZSE_TICK_MS_TAIL = 10 # 深交所时戳,尾部毫秒精度,以10ms为单位
class SIDE(Enum): # 2bit
BID = 0
ASK = 1
UNKNOWN = -1 # 仅用于测试
def __str__(self):
if self.value==0:
return 'BID'
elif self.value==1:
return 'ASK'
else:
return 'UNKNOWN'
class TYPE(Enum): # 2bit
LIMIT = 0 #限价
MARKET = 1 #市价
SIDE = 2 #本方最优
UNKNOWN = -1 # 仅用于测试
# 用于将原始精度转换到ob精度
SZSE_STOCK_PRICE_RD = msg_util.PRICE_SZSE_INCR_PRECISION // PRICE_INTER_STOCK_PRECISION
SZSE_FUND_PRICE_RD = msg_util.PRICE_SZSE_INCR_PRECISION // PRICE_INTER_FUND_PRECISION
SSE_STOCK_PRICE_RD = msg_util.PRICE_SSE_PRECISION // PRICE_INTER_STOCK_PRECISION
# SSE_FUND_PRICE_RD = msg_util.PRICE_SSE_PRECISION // PRICE_INTER_FUND_PRECISION TODO:确认精度 [low priority]
class ob_order():
'''专注于内部使用的字段格式与位宽'''
__slots__ = [
'applSeqNum',
'price',
'qty',
'side',
'type',
# for test olny
'traded',
'TransactTime',
]
def __init__(self, order:axsbe_order, instrument_type:INSTRUMENT_TYPE):
# self.securityID = order.SecurityID
self.applSeqNum = order.ApplSeqNum
if order.SecurityIDSource==SecurityIDSource_SZSE:
if instrument_type==INSTRUMENT_TYPE.STOCK:
self.price = order.Price // SZSE_STOCK_PRICE_RD # 深圳 N13(4),实际股票精度为分
elif instrument_type==INSTRUMENT_TYPE.FUND:
self.price = order.Price // SZSE_FUND_PRICE_RD # 深圳 N13(4),实际基金精度为厘
else:
axob_logger.error(f'order SZSE ApplSeqNum={order.ApplSeqNum} instrument_type={instrument_type} not support!')
elif order.SecurityIDSource==SecurityIDSource_SSE:
if instrument_type==INSTRUMENT_TYPE.STOCK:
self.price = order.Price // SSE_STOCK_PRICE_RD # 上海 原始数据3位小数
else:
axob_logger.error(f'order SSE ApplSeqNum={order.ApplSeqNum} instrument_type={instrument_type} not support!')
else:
self.price = 0
self.traded = False #仅用于测试:市价单,当有成交后,市价单的价格将确定
self.TransactTime = order.TransactTime #仅用于测试:市价单,当有后续消息来而导致插入订单簿时,生成的订单簿用此时戳
self.qty = order.OrderQty # 深圳2位小数;上海3位小数
if order.Side_str=='买入':
self.side = SIDE.BID
elif order.Side_str=='卖出':
self.side = SIDE.ASK
else:
'''TODO-SSE'''
self.side = SIDE.UNKNOWN
if order.Type_str=='限价':
self.type = TYPE.LIMIT
elif order.Type_str=='市价':
self.type = TYPE.MARKET
elif order.Type_str=='本方最优':
self.type = TYPE.SIDE
else:
'''TODO-SSE'''
self.type = TYPE.UNKNOWN
## 位宽及精度舍入可行性检查
if self.applSeqNum >= (1<<APPSEQ_BIT_SIZE) and self.applSeqNum!=0xffffffffffffffff:
axob_logger.error(f'{order.SecurityID:06d} order ApplSeqNum={order.ApplSeqNum} ovf!')
if self.price >= (1<<PRICE_BIT_SIZE):
self.price = (1<<PRICE_BIT_SIZE)-1
axob_logger.error(f'{order.SecurityID:06d} order ApplSeqNum={order.ApplSeqNum} Price={order.Price} ovf!') # 无涨跌停价时可能,即使限价单也可能溢出,且会被前端处理成0x7fff_ffff
if self.qty >= (1<<QTY_BIT_SIZE):
axob_logger.error(f'{order.SecurityID:06d} order ApplSeqNum={order.ApplSeqNum} Volumn={order.OrderQty} ovf!')
if self.type==TYPE.LIMIT: #检查限价单价格是否溢出;市价单价格是无效值,不可参与检查
if order.SecurityIDSource==SecurityIDSource_SZSE:
if instrument_type==INSTRUMENT_TYPE.STOCK and order.Price % SZSE_STOCK_PRICE_RD:
axob_logger.error(f'{order.SecurityID:06d} order SZSE STOCK ApplSeqNum={order.ApplSeqNum} Price={order.Price} precision dnf!') #当被前端处理成0x7fff_ffff时 会有余数
elif instrument_type==INSTRUMENT_TYPE.FUND and order.Price % SZSE_FUND_PRICE_RD:
axob_logger.error(f'{order.SecurityID:06d} order SZSE FUND ApplSeqNum={order.ApplSeqNum} Price={order.Price} precision dnf!') #当被前端处理成0x7fff_ffff时 会有余数
elif order.SecurityIDSource==SecurityIDSource_SSE:
if instrument_type==INSTRUMENT_TYPE.STOCK and order.Price % SSE_STOCK_PRICE_RD:
axob_logger.error(f'{order.SecurityID:06d} order SSE STOCK ApplSeqNum={order.ApplSeqNum} Price={order.Price} precision dnf!')
def save(self):
'''save/load 用于保存/加载测试时刻'''
data = {}
for attr in self.__slots__:
value = getattr(self, attr)
data[attr] = value
return data
def load(self, data):
for attr in self.__slots__:
setattr(self, attr, data[attr])
class ob_exec():
'''专注于内部使用的字段格式与位宽'''
__slots__ = [
'LastPx',
'LastQty',
'BidApplSeqNum',
'OfferApplSeqNum',
# for test olny
'TransactTime',
]
def __init__(self, exec:axsbe_exe, instrument_type:INSTRUMENT_TYPE):
self.BidApplSeqNum = exec.BidApplSeqNum
self.OfferApplSeqNum = exec.OfferApplSeqNum
if exec.SecurityIDSource==SecurityIDSource_SZSE:
if instrument_type==INSTRUMENT_TYPE.STOCK:
self.LastPx = exec.LastPx // SZSE_STOCK_PRICE_RD # 深圳 N13(4),实际股票精度为分
elif instrument_type==INSTRUMENT_TYPE.FUND:
self.LastPx = exec.LastPx // SZSE_FUND_PRICE_RD # 深圳 N13(4),实际基金精度为厘
else:
axob_logger.error(f'exec SZSE ApplSeqNum={exec.ApplSeqNum} instrument_type={instrument_type} not support!')
elif exec.SecurityIDSource==SecurityIDSource_SSE:
if instrument_type==INSTRUMENT_TYPE.STOCK:
self.LastPx = exec.LastPx // SSE_STOCK_PRICE_RD # 上海 原始数据3位小数
else:
axob_logger.error(f'order SSE ApplSeqNum={exec.ApplSeqNum} instrument_type={instrument_type} not support!')
else:
self.LastPx = 0
self.LastQty = exec.LastQty # 深圳2位小数;上海3位小数
self.TransactTime = exec.TransactTime
## 位宽及精度舍入可行性检查
# 不去检查SeqNum位宽了,SeqNum总能在order list中找到,因此肯定已经检查过了。
# price/qty同理
# if self.LastPx >= (1<<PRICE_BIT_SIZE):
# axob_logger.error(f'{exec.SecurityID:06d} order ApplSeqNum={exec.ApplSeqNum} LastPx={exec.LastPx} ovf!') # 无涨跌停价时可能,即使限价单也可能溢出,且会被前端处理成0x7fff_ffff
# if self.LastQty >= (1<<QTY_BIT_SIZE):
# axob_logger.error(f'{exec.SecurityID:06d} order ApplSeqNum={exec.ApplSeqNum} LastQty={exec.LastQty} ovf!')
class ob_cancel():
'''专注于内部使用的字段格式与位宽'''
__slots__ = [
'applSeqNum',
'qty',
'price',
'side',
# for test olny
'TransactTime',
]
def __init__(self, ApplSeqNum, Qty, Price, Side, TransactTime, SecurityIDSource, instrument_type, SecurityID):
self.applSeqNum = ApplSeqNum #
self.qty = Qty
if SecurityIDSource==SecurityIDSource_SZSE:
self.price = 0 #深圳撤单不带价格
elif SecurityIDSource==SecurityIDSource_SSE:
if instrument_type==INSTRUMENT_TYPE.STOCK:
self.price = Price // SSE_STOCK_PRICE_RD # 上海 原始数据3位小数
else:
axob_logger.error(f'{SecurityID:06d} cancel SSE ApplSeqNum={ApplSeqNum} instrument_type={instrument_type} not support!')
else:
axob_logger.error(f'{SecurityID:06d} cancel ApplSeqNum={ApplSeqNum} SecurityIDSource={SecurityIDSource} unknown!')
self.side = Side
self.TransactTime = TransactTime
if self.applSeqNum >= (1<<APPSEQ_BIT_SIZE):
axob_logger.error(f'{SecurityID:06d} cancel ApplSeqNum={ApplSeqNum} ovf!')
if self.price >= (1<<PRICE_BIT_SIZE):
axob_logger.error(f'{SecurityID:06d} cancel ApplSeqNum={ApplSeqNum} Price={Price} ovf!')
if self.qty >= (1<<QTY_BIT_SIZE):
axob_logger.error(f'{SecurityID:06d} cancel ApplSeqNum={ApplSeqNum} Volumn={Qty} ovf!')
class level_node():
__slots__ = [
'price',
'qty',
# for test olny
# 'ts',
]
def __init__(self, price, qty, ts):
self.price = price
self.qty = qty
# 目前没用,仅供调试
# self.ts = [ts] 目前已经无法维护序列号了,因为没有去检查成交是部分成交还是全部成交
def save(self):
'''save/load 用于保存/加载测试时刻'''
data = {}
for attr in self.__slots__:
value = getattr(self, attr)
if attr=='ts':
data[attr] = deepcopy(value)
else:
data[attr] = value
return data
def load(self, data):
for attr in self.__slots__:
setattr(self, attr, data[attr])
def __str__(self) -> str:
return f'{self.price}\t{self.qty}'
class AX_SIGNAL(Enum): # 发送给AXOB的信号
OPENCALL_BGN = 0 # 开盘集合竞价开始
OPENCALL_END = 1 # 开盘集合竞价结束
AMTRADING_BGN = 2 # 上午连续竞价开始
AMTRADING_END = 3 # 上午连续竞价结束
PMTRADING_BGN = 4 # 下午连续竞价开始
PMTRADING_END = 5 # 下午连续竞价结束
ALL_END = 6 # 闭市
VB_BGN = 7 # 进入波动性中断
VB_END = 8 # 退出波动性中断
class CAGE(Enum):
NONE = 0
CYB = 1 # 创业板价格笼子
class CAGE_SIDE(Enum):
NONE = 1
BID = 2
ASK = 3
class AXOB():
__slots__ = [
'SecurityID',
'SecurityIDSource',
'instrument_type',
'order_map', # map of ob_order
'bid_level_tree', # map of level_node
'ask_level_tree', # map of level_node
'NumTrades',
'bid_max_level_price',
'bid_max_level_qty',
'ask_min_level_price',
'ask_min_level_qty',
'LastPx',
'HighPx',
'LowPx',
'OpenPx',
'closePx_ready',
'ChannelNo',
'PrevClosePx',
'DnLimitPx',
'UpLimitPx',
'DnLimitPrice',
'UpLimitPrice',
'YYMMDD',
'current_inc_tick',
'BidWeightSize',
'BidWeightValue',
'AskWeightSize',
'AskWeightValue',
'AskWeightSizeEx',
'AskWeightValueEx',
'TotalVolumeTrade',
'TotalValueTrade',
'holding_order',
'holding_nb',
'TradingPhaseMarket',
'VolatilityBreaking_end_tick',
'cage_type',
'bid_cage_upper_ex_min_level_price',
'bid_cage_upper_ex_min_level_qty',
'ask_cage_lower_ex_max_level_price',
'ask_cage_lower_ex_max_level_qty',
'bid_cage_ref_px',
'ask_cage_ref_px',
'bid_waiting_for_cage',
'ask_waiting_for_cage',
# profile
'pf_order_map_maxSize',
'pf_level_tree_maxSize',
'pf_bid_level_tree_maxSize',
'pf_ask_level_tree_maxSize',
# for test olny
'msg_nb',
'rebuilt_snaps', # list of snap
'market_snaps', # list of snap
'last_snap',
'last_inc_applSeqNum',
'logger',
'DBG',
'INFO',
'WARN',
'ERR',
]
def __init__(self, SecurityID:int, SecurityIDSource, instrument_type:INSTRUMENT_TYPE, load_data=None):
'''
TODO: holding_order的处理是否统一到一处?
TODO: 增加时戳输入,用于结算各自缓存,如市价单
'''
if load_data:
self.load(load_data)
else:
self.SecurityID = SecurityID
self.SecurityIDSource = SecurityIDSource #"证券代码源101=上交所;102=深交所;103=香港交易所" 在hls中用宏或作为模板参数设置
self.instrument_type = instrument_type
## 结构数据:
self.order_map = {} #订单队列,以applSeqNum作为索引
self.bid_level_tree = {} #买方价格档,以价格作为索引
self.ask_level_tree = {} #卖方价格档
self.NumTrades = 0
self.bid_max_level_price = 0
self.bid_max_level_qty = 0
self.ask_min_level_price = 0
self.ask_min_level_qty = 0
self.LastPx = 0
self.HighPx = 0
self.LowPx = 0
self.OpenPx = 0
self.closePx_ready = False
self.ChannelNo = 0 #来自于快照
self.PrevClosePx = 0 #来自于快照 深圳要处理到内部精度,用于在还原快照时比较
self.DnLimitPx = 0 # #来自于快照 无涨跌停价时为0x7fffffff
self.UpLimitPx = 0 # #来自于快照 无涨跌停价时为100
self.DnLimitPrice = 0
self.UpLimitPrice = 0
self.YYMMDD = 0 #来自于快照
self.current_inc_tick = 0 #来自于逐笔 时-分-秒-10ms
self.BidWeightSize = 0
self.BidWeightValue = 0
self.AskWeightSize = 0
self.AskWeightValue = 0
self.AskWeightSizeEx = 0
self.AskWeightValueEx = 0
self.TotalVolumeTrade = 0
self.TotalValueTrade = 0
self.holding_order = None
self.holding_nb = 0
self.TradingPhaseMarket = axsbe_base.TPM.Starting
self.VolatilityBreaking_end_tick = 0
## 创业板价格笼子 http://docs.static.szse.cn/www/disclosure/notice/general/W020200612831351578076.pdf
if SecurityIDSource==SecurityIDSource_SZSE and SecurityID>=300000 and SecurityID<309999: #创业板
self.cage_type = CAGE.CYB
else:
self.cage_type = CAGE.NONE
self.bid_cage_upper_ex_min_level_price = 0 #买方价格笼子上沿之外的最低价,超过买入基准价的102%
self.bid_cage_upper_ex_min_level_qty = 0
self.ask_cage_lower_ex_max_level_price = 0 #卖方价格笼子下沿之外的最高价,低于卖出基准价的98%
self.ask_cage_lower_ex_max_level_qty = 0
self.bid_cage_ref_px = 0 #买方价格笼子基准价格 卖方一档价格 -> 买方一档价格 -> 最近成交价 -> 前收盘价,小于等于基准价的102%的在笼子内,大于的在笼子外(被隐藏)
self.ask_cage_ref_px = 0 #卖方价格笼子基准价格 买方一档价格 -> 卖方一档价格 -> 最近成交价 -> 前收盘价,大于等于基准价的98%的在笼子内,小于的在笼子外(被隐藏)
self.bid_waiting_for_cage = False
self.ask_waiting_for_cage = False
## 调试数据,仅用于测试算法是否正确:
self.pf_order_map_maxSize = 0
self.pf_level_tree_maxSize = 0
self.pf_bid_level_tree_maxSize = 0
self.pf_ask_level_tree_maxSize = 0
self.msg_nb = 0
self.rebuilt_snaps = {}
self.market_snaps = {}
self.last_snap = None
self.last_inc_applSeqNum = 0
## 日志
self.logger = logging.getLogger(f'{self.SecurityID:06d}')
g_logger = logging.getLogger('main')
self.logger.setLevel(g_logger.getEffectiveLevel())
for h in g_logger.handlers:
self.logger.addHandler(h)
axob_logger.addHandler(h) #这里补上模块日志的handler,有点ugly TODO: better way [low prioryty]
self.DBG = self.logger.debug
self.INFO = self.logger.info
self.WARN = self.logger.warning
self.ERR = self.logger.error
def onMsg(self, msg):
'''处理总入口'''
if isinstance(msg, (axsbe_order, axsbe_exe, axsbe_snap_stock)):
if msg.SecurityID!=self.SecurityID:
return
if isinstance(msg, (axsbe_order, axsbe_exe)):
if self.cage_type==CAGE.CYB and self.TradingPhaseMarket==axsbe_base.TPM.PMTrading and msg.TradingPhaseMarket==axsbe_base.TPM.CloseCall:
# 创业板进入收盘集合竞价,敞开价格笼子,将外面的隐藏订单放进来
self.openCage()
self._useTimestamp(msg.TransactTime)
if self.TradingPhaseMarket!=axsbe_base.TPM.VolatilityBreaking:
self.TradingPhaseMarket = msg.TradingPhaseMarket # 只用逐笔,在阶段切换期间,逐笔和快照的速率不同,可能快照切了逐笔没切,或反过来,
# 由于我们重建完全基于逐笔,快照仅用来做检查,故阶段切换基于逐笔。
# 几个例外情况:
# 在开盘集合竞价结束时可能没有成交;在进入中午休市时,没有逐笔。
# 此时由更高层触发SIGNAL。
# else:
# if self.VolatilityBreaking_end_tick==0: #波动性中断期间,逐笔成交到来说明中断结束
# if isinstance(msg, axsbe_exe) and msg.ExecType_str=='成交':
# self.VolatilityBreaking_end_tick = self.current_inc_tick
# else:
# if not(isinstance(msg, axsbe_exe) and msg.ExecType_str=='成交'): #中断结束后,有非逐笔成交
# self.TradingPhaseMarket = msg.TradingPhaseMarket
if isinstance(msg, axsbe_order):
self.onOrder(msg)
elif isinstance(msg, axsbe_exe):
self.onExec(msg)
else:# isinstance(msg, axsbe_snap_stock):
self.onSnap(msg)
if isinstance(msg, (axsbe_order, axsbe_exe)):
self.last_inc_applSeqNum = msg.ApplSeqNum
elif isinstance(msg, AX_SIGNAL):
if msg==AX_SIGNAL.OPENCALL_END:
if self.bid_max_level_price<self.ask_min_level_price and self.TradingPhaseMarket==axsbe_base.TPM.OpenCall: #双方最优价无法成交,否则等成交
self.TradingPhaseMarket = axsbe_base.TPM.PreTradingBreaking #自行修改交易阶段,使生成的快照为交易快照
self.genSnap()
elif msg==AX_SIGNAL.AMTRADING_BGN:
if self.TradingPhaseMarket==axsbe_base.TPM.PreTradingBreaking:
self.AskWeightSize += self.AskWeightSizeEx
self.AskWeightValue += self.AskWeightValueEx
self.TradingPhaseMarket = axsbe_base.TPM.AMTrading
self.genSnap()
elif msg==AX_SIGNAL.AMTRADING_END:
if self.TradingPhaseMarket==axsbe_base.TPM.AMTrading:
if self.holding_nb==0: #不再有缓存单
self.TradingPhaseMarket = axsbe_base.TPM.Breaking #自行修改交易阶段,使生成的快照为交易快照
self.genSnap()
elif msg==AX_SIGNAL.PMTRADING_END:
if self.holding_nb==0 and self.TradingPhaseMarket==axsbe_base.TPM.PMTrading: #不再有缓存单
self.TradingPhaseMarket = axsbe_base.TPM.CloseCall #自行修改交易阶段,使生成的快照为交易快照
self.openCage() #先打开笼子,再生成快照
self.genSnap()
elif msg==AX_SIGNAL.ALL_END:
# 收盘集合竞价结束,收盘价:
# 沪市收盘价为当日该证券最后一笔交易前一分钟所有交易的成交量加权平均价(含最后一笔交易)。当日无成交的,以前收盘价为当日收盘价。
# 深市的收盘价通过集合竞价的方式产生。收盘集合竞价不能产生收盘价的,以当日该证券最后一笔交易前一分钟所有交易的成交量加权平均价(含最后一笔交易)为收盘价。当日无成交的,以前收盘价为当日收盘价。
if self.SecurityIDSource==SecurityIDSource_SZSE:
if self.bid_max_level_price<self.ask_min_level_price and self.TradingPhaseMarket==axsbe_base.TPM.CloseCall: #双方最优价无法成交,否则等成交
self.TradingPhaseMarket = axsbe_base.TPM.Ending #自行修改交易阶段,使生成的快照为交易快照
self.closePx_ready = False #等快照的价格作为最后价格
else:
self.closePx_ready = True #直接生成快照
self.genSnap()
else:
if self.bid_max_level_price<self.ask_min_level_price and self.TradingPhaseMarket==axsbe_base.TPM.CloseCall: #双方最优价无法成交,否则等成交
self.TradingPhaseMarket = axsbe_base.TPM.Ending #自行修改交易阶段,使生成的快照为交易快照
self.closePx_ready = False #等快照的价格作为最后价格
else:
pass
#if self.TradingPhaseMarket>=axsbe_base.TPM.Ending:
# if self.msg_nb==143198:
# self._print_levels()
## 调试数据,仅用于测试算法是否正确:
self.msg_nb += 1
self.profile()
if len(self.ask_level_tree):
if self.cage_type==CAGE.CYB and self.ask_cage_lower_ex_max_level_qty:
assert self.ask_min_level_price>self.ask_cage_lower_ex_max_level_price, f'{self.SecurityID:06d} cache ask-min-price/cage-max NG'
else:
assert self.ask_min_level_price==min(self.ask_level_tree.keys()), f'{self.SecurityID:06d} cache ask-min-price NG'
assert self.ask_min_level_qty==min(self.ask_level_tree.items(), key=lambda x: x[0])[1].qty, f'{self.SecurityID:06d} cache ask-min-qty NG'
if len(self.bid_level_tree):
if self.cage_type==CAGE.CYB and self.bid_cage_upper_ex_min_level_qty:
assert self.bid_max_level_price<self.bid_cage_upper_ex_min_level_price, f'{self.SecurityID:06d} cache bid-max-price/cage-min NG'
else:
assert self.bid_max_level_price==max(self.bid_level_tree.keys()), f'{self.SecurityID:06d} cache bid-max-price NG'
assert self.bid_max_level_qty==max(self.bid_level_tree.items(), key=lambda x: x[0])[1].qty, f'{self.SecurityID:06d} ache bid-max-qty NG'
if (self.TradingPhaseMarket==axsbe_base.TPM.AMTrading or self.TradingPhaseMarket==axsbe_base.TPM.PMTrading) and self.bid_max_level_qty and self.ask_min_level_qty:
assert self.bid_max_level_price<self.ask_min_level_price, f'{self.SecurityID:06d} bid.max({self.bid_max_level_price})/ask.min({self.ask_min_level_price}) NG'
static_AskWeightSize = 0
static_AskWeightValue = 0
for _,l in self.ask_level_tree.items():
assert l.qty<(1<<LEVEL_QTY_BIT_SIZE), f'{self.SecurityID:06d} ask level qty={l.qty} ovf @{self.current_inc_tick}'
if (self.ask_cage_lower_ex_max_level_qty==0 or l.price>self.ask_cage_lower_ex_max_level_price):
static_AskWeightSize += l.qty
static_AskWeightValue += l.price * l.qty
if self.TradingPhaseMarket>=axsbe_base.TPM.AMTrading:
assert static_AskWeightSize==self.AskWeightSize, f'{self.SecurityID:06d} static AskWeightSize={static_AskWeightSize}, dynamic AskWeightSize={self.AskWeightSize}'
assert static_AskWeightValue==self.AskWeightValue, f'{self.SecurityID:06d} static AskWeightSize={static_AskWeightValue}, dynamic AskWeightValue={self.AskWeightValue}'
else:
assert static_AskWeightSize==self.AskWeightSize + self.AskWeightSizeEx, f'{self.SecurityID:06d} static AskWeightSize={static_AskWeightSize}, dynamic AskWeightSize={self.AskWeightSize}+{self.AskWeightSizeEx}'
assert static_AskWeightValue==self.AskWeightValue + self.AskWeightValueEx, f'{self.SecurityID:06d} static AskWeightSize={static_AskWeightValue}, dynamic AskWeightValue={self.AskWeightValue}+{self.AskWeightValueEx}'
static_BidWeightSize = 0
static_BidWeightValue = 0
for _,l in self.bid_level_tree.items():
assert l.qty<(1<<LEVEL_QTY_BIT_SIZE), f'{self.SecurityID:06d} bid level qty={l.qty} ovf @{self.current_inc_tick}'
if self.bid_cage_upper_ex_min_level_qty==0 or l.price<self.bid_cage_upper_ex_min_level_price:
static_BidWeightSize += l.qty
static_BidWeightValue += l.price * l.qty
assert static_BidWeightSize==self.BidWeightSize, f'{self.SecurityID:06d} static BidWeightSize={static_BidWeightSize}, dynamic BidWeightSize={self.BidWeightSize}'
assert static_BidWeightValue==self.BidWeightValue, f'{self.SecurityID:06d} static BidWeightValue={self.BidWeightValue}, dynamic BidWeightValue={self.BidWeightValue}'
for _,ls in self.market_snaps.items():
assert len(ls)!=0, f'{self.SecurityID:06d} market snap not pop clean'
def openCage(self):
self.DBG('openCage')
# self._print_levels()
## 创业板上市头5日连续竞价、复牌集合竞价、收盘集合竞价的有效竞价范围是最近成交价的上下10%
if self.UpLimitPx==2147483647: #无涨跌停限制=创业板上市头5日 TODO: 更精确
ex_p = []
for p, l in sorted(self.ask_level_tree.items(),key=lambda x:x[0], reverse=False): #从小到大遍历
if p>msg_util.CYB_match_upper(self.LastPx) or p<msg_util.CYB_match_lower(self.LastPx):
ex_p.append(p)
if p>self.ask_cage_lower_ex_max_level_price:
self.AskWeightSize -= l.qty
self.AskWeightValue -= p * l.qty
for p in ex_p:
self.ask_level_tree.pop(p)
ex_p = []
for p, l in sorted(self.bid_level_tree.items(),key=lambda x:x[0], reverse=True): #从大到小遍历
if p>msg_util.CYB_match_upper(self.LastPx) or p<msg_util.CYB_match_lower(self.LastPx):
ex_p.append(p)
if p<self.bid_cage_upper_ex_min_level_price:
self.BidWeightSize -= l.qty
self.BidWeightValue -= p * l.qty
for p in ex_p:
self.bid_level_tree.pop(p)
if self.ask_cage_lower_ex_max_level_qty:
for p, l in sorted(self.ask_level_tree.items(),key=lambda x:x[0], reverse=False): #从小到大遍历
if p<=self.ask_cage_lower_ex_max_level_price:
self.AskWeightSize += l.qty
self.AskWeightValue += p * l.qty
else:
break
self.ask_cage_lower_ex_max_level_qty = 0
self.ask_min_level_price = min(self.ask_level_tree.keys())
self.ask_min_level_qty = self.ask_level_tree[self.ask_min_level_price].qty
if self.bid_cage_upper_ex_min_level_qty:
for p, l in sorted(self.bid_level_tree.items(),key=lambda x:x[0], reverse=True): #从大到小遍历
if p>=self.bid_cage_upper_ex_min_level_price:
self.BidWeightSize += l.qty
self.BidWeightValue += p * l.qty
else:
break
self.bid_cage_upper_ex_min_level_qty = 0
self.bid_max_level_price = max(self.bid_level_tree.keys())
self.bid_max_level_qty = self.bid_level_tree[self.bid_max_level_price].qty
# self._print_levels()
def onOrder(self, order:axsbe_order):
'''
逐笔订单入口,统一提取市价单、限价单的关键字段到内部订单格式
跳转到处理限价单或处理撤单
'''
self.DBG(f'msg#{self.msg_nb} onOrder:{order}')
if self.SecurityIDSource == SecurityIDSource_SZSE:
_order = ob_order(order, self.instrument_type)
elif self.SecurityIDSource == SecurityIDSource_SSE:
'''TODO-SSE'''
# order or cancel
else:
return
if _order.type==TYPE.MARKET:
# 市价单,都必须在开盘之后
if self.bid_max_level_qty==0 and self.ask_min_level_qty==0:
raise '未定义模式:市价单早于价格档' #TODO: cover [Mid priority]
# 市价单,几种可能:
# * 对手方最优价格申报:有成交、最后挂在对方一档或者二档,需要等时戳切换、新委托、新撤单到来的时候插入快照
# * 最优五档即时成交剩余撤销申报:最后有撤单
# * 即时成交剩余撤销申报:最后有撤单
# * 全额成交或撤销申报:最后有撤单
elif _order.type==TYPE.SIDE:
# 本方最优价格申报 转限价单
if _order.side==SIDE.BID:
if self.bid_max_level_price!=0 and self.bid_max_level_qty!=0: #本方有量
_order.price = self.bid_max_level_price
else:
_order.price = self.DnLimitPrice
self.WARN(f'order #{_order.applSeqNum} 本方最优买单 但无本方价格!')
else:
if self.ask_min_level_price!=0 and self.ask_min_level_qty!=0: #本方有量
_order.price = self.ask_min_level_price
else:
_order.price = self.UpLimitPrice
self.WARN(f'order #{_order.applSeqNum} 本方最优卖单 但无本方价格!')
else:
pass
self.onLimitOrder(_order)
def onLimitOrder(self, order:ob_order):
if self.TradingPhaseMarket==axsbe_base.TPM.OpenCall or self.TradingPhaseMarket==axsbe_base.TPM.CloseCall:
#集合竞价期间,直接插入
if self.TradingPhaseMarket==axsbe_base.TPM.CloseCall and self.holding_nb!=0: #进入收盘集合竞价,但可能有市价单还在确认
self.insertOrder(self.holding_order)
self.holding_nb = 0
if self.TradingPhaseMarket==axsbe_base.TPM.CloseCall and self.UpLimitPx==2147483647 and\
(order.price>msg_util.CYB_match_upper(self.LastPx) or order.price<msg_util.CYB_match_lower(self.LastPx)):
pass # 创业板上市头5日超出范围则丢弃
else:
self.insertOrder(order)
self.bid_waiting_for_cage = False
self.ask_waiting_for_cage = False
self.genSnap() #可出snap
else:
if self.holding_nb!=0: #把此前缓存的订单(市价/限价)插入LOB
if self.holding_order.type == TYPE.MARKET and not self.holding_order.traded:
self.ERR(f'市价单 {self.holding_order} 未伴随成交')
self.insertOrder(self.holding_order)
self.holding_nb = 0
self._useTimestamp(self.holding_order.TransactTime)
self.genSnap() #先出一个snap,时戳用市价单的
self._useTimestamp(order.TransactTime)
if self.cage_type==CAGE.CYB and order.type==TYPE.LIMIT and\
(order.side==SIDE.BID and (order.price>CYB_cage_upper(self.bid_cage_ref_px)) or
order.side==SIDE.ASK and (order.price<CYB_cage_lower(self.ask_cage_ref_px))):
self.insertOrder(order, outOfCage=True)
self.genSnap() #出一个snap
elif self.TradingPhaseMarket==axsbe_base.TPM.VolatilityBreaking:
#波动性中断(有新order表示临停结束,正在集合竞价),直接插入
self.insertOrder(order)
self.genSnap() #可出snap
else:
#若是市价单或可能成交的限价单,则缓存住,等成交
if order.type==TYPE.MARKET:
self.holding_order = order
self.holding_nb += 1
self.DBG('hold MARET-order')
elif (order.side==SIDE.BID and (order.price >= self.ask_min_level_price and self.ask_min_level_qty > 0)) or \
(order.side==SIDE.ASK and (order.price <= self.bid_max_level_price and self.bid_max_level_qty > 0)):
self.holding_order = order
self.holding_nb += 1
self.DBG('hold LIMIT-order')
self.bid_waiting_for_cage = False
self.ask_waiting_for_cage = False
else:
self.insertOrder(order)
if self.cage_type==CAGE.CYB:
self.enterCage()
self.genSnap() #再出一个snap
def insertOrder(self, order:ob_order, outOfCage=False):
'''
订单入列,更新对应的价格档位数据
outOfCage:入列的订单不在价格笼子内(服务器将隐藏订单,不影响当前最优档)
'''
self.order_map[order.applSeqNum] = order
if order.side == SIDE.BID:
if order.price in self.bid_level_tree:
self.bid_level_tree[order.price].qty += order.qty
if order.price==self.bid_max_level_price:
self.bid_max_level_qty += order.qty
if self.bid_cage_upper_ex_min_level_qty and order.price==self.bid_cage_upper_ex_min_level_price:
self.bid_cage_upper_ex_min_level_qty += order.qty
else:
node = level_node(order.price, order.qty, order.applSeqNum)
self.bid_level_tree[order.price] = node
if not outOfCage:
if self.bid_max_level_qty==0 or order.price>self.bid_max_level_price: #买方出现更高价格
self.bid_max_level_price = order.price
self.bid_max_level_qty = order.qty
self.ask_cage_ref_px = order.price
self.DBG(f'Ask cage ref px={self.ask_cage_ref_px}')
self.ask_waiting_for_cage = True if self.cage_type==CAGE.CYB else False
else:
self.DBG('Bid order out of cage.')
if order.price>self.bid_cage_ref_px and\
(self.bid_cage_upper_ex_min_level_qty==0 or order.price<self.bid_cage_upper_ex_min_level_price): #买方笼子之上出现更低价
self.bid_cage_upper_ex_min_level_price = order.price
self.bid_cage_upper_ex_min_level_qty = order.qty
self.DBG(f'Refresh bid_cage_upper_ex_min_level_price={self.bid_cage_upper_ex_min_level_price} by new price')
if not outOfCage:
self.BidWeightSize += order.qty
self.BidWeightValue += order.price * order.qty
elif order.side == SIDE.ASK:
if order.price in self.ask_level_tree:
self.ask_level_tree[order.price].qty += order.qty
if order.price==self.ask_min_level_price:
self.ask_min_level_qty += order.qty
if self.ask_cage_lower_ex_max_level_qty and order.price==self.ask_cage_lower_ex_max_level_price:
self.ask_cage_lower_ex_max_level_qty += order.qty
else:
node = level_node(order.price, order.qty, order.applSeqNum)
self.ask_level_tree[order.price] = node
if not outOfCage:
if self.ask_min_level_qty==0 or order.price<self.ask_min_level_price: #卖方出现更低价格
self.ask_min_level_price = order.price
self.ask_min_level_qty = order.qty
self.bid_cage_ref_px = order.price
self.DBG(f'Bid cage ref px={self.bid_cage_ref_px}')
self.bid_waiting_for_cage = True if self.cage_type==CAGE.CYB else False
else:
self.DBG('Ask order out of cage.')
if order.price<self.ask_cage_ref_px and\
(self.ask_cage_lower_ex_max_level_qty==0 or order.price>self.ask_cage_lower_ex_max_level_price): #买方笼子之下出现更高价
self.ask_cage_lower_ex_max_level_price = order.price
self.ask_cage_lower_ex_max_level_qty = order.qty
self.DBG(f'Refresh ask_cage_lower_ex_max_level_price={self.ask_cage_lower_ex_max_level_price} by new price')
if not outOfCage:
if self.TradingPhaseMarket==axsbe_base.TPM.OpenCall and order.price>self.PrevClosePx*10: #从深交所数据上看,超过昨收(新股时为上市价)10倍的委托不会参与统计
self.AskWeightSizeEx += order.qty
self.AskWeightValueEx += order.price * order.qty
# if order.price<self.PrevClosePx*10 and order.price!=(1<<PRICE_BIT_SIZE)-1:
else:
self.AskWeightSize += order.qty
self.AskWeightValue += order.price * order.qty
def onExec(self, exec:axsbe_exe):
'''
逐笔成交入口
跳转到处理成交或处理撤单
'''
self.DBG(f'msg#{self.msg_nb} onExec:{exec}')
if exec.ExecType_str=='成交' or self.SecurityIDSource==SecurityIDSource_SSE:
_exec = ob_exec(exec, self.instrument_type)
self.onTrade(_exec)
else:
#only SecurityIDSource_SZSE
if exec.BidApplSeqNum!=0: # 撤销bid
cancel_seq = exec.BidApplSeqNum
Side = SIDE.BID
else: # 撤销ask
cancel_seq = exec.OfferApplSeqNum
Side = SIDE.ASK
_cancel = ob_cancel(cancel_seq, exec.LastQty, exec.LastPx, Side, exec.TransactTime, self.SecurityIDSource, self.instrument_type, self.SecurityID)
self.onCancel(_cancel)
def onTrade(self, exec:ob_exec):
'''处理成交消息'''
#
self.NumTrades += 1
self.TotalVolumeTrade += exec.LastQty
if self.SecurityIDSource==SecurityIDSource_SZSE:
# 乘法输入:深圳(Qty精度2位、price精度2位or3位小数);输出TotalValueTrade深圳(精度4位小数)
if self.instrument_type==INSTRUMENT_TYPE.STOCK:
self.TotalValueTrade += int(exec.LastQty * exec.LastPx/(QTY_INTER_SZSE_PRECISION*PRICE_INTER_STOCK_PRECISION // msg_util.TOTALVALUETRADE_SZSE_PRECISION)) # 2x2->4
elif self.instrument_type==INSTRUMENT_TYPE.FUND:
self.TotalValueTrade += int(exec.LastQty * exec.LastPx/(QTY_INTER_SZSE_PRECISION*PRICE_INTER_FUND_PRECISION // msg_util.TOTALVALUETRADE_SZSE_PRECISION)) # 2x3->4
else:
self.TotalValueTrade += None
elif self.SecurityIDSource==SecurityIDSource_SSE:
# 乘法输入:上海(Qty精度3位、price精度2位or3位小数);输出TotalValueTrade上海(精度5位小数)
if self.instrument_type==INSTRUMENT_TYPE.STOCK:
self.TotalValueTrade += int(exec.LastQty * exec.LastPx/(QTY_INTER_SSE_PRECISION*PRICE_INTER_STOCK_PRECISION // msg_util.TOTALVALUETRADE_SSE_PRECISION)) # 3x2 -> 5
elif self.instrument_type==INSTRUMENT_TYPE.FUND:
self.TotalValueTrade += int(exec.LastQty * exec.LastPx/(QTY_INTER_SSE_PRECISION*PRICE_INTER_FUND_PRECISION // msg_util.TOTALVALUETRADE_SZSE_PRECISION)) # 3x3->5
else:
self.TotalValueTrade += None
else:
self.TotalValueTrade += None
self.LastPx = exec.LastPx
if self.OpenPx == 0:
self.OpenPx = exec.LastPx
self.HighPx = exec.LastPx
self.LowPx = exec.LastPx
else:
if self.HighPx < exec.LastPx:
self.HighPx = exec.LastPx
if self.LowPx > exec.LastPx:
self.LowPx = exec.LastPx
#有可能市价单剩余部分进队列,后续成交是由价格笼子外的订单造成的
if self.holding_nb and self.holding_order.type==TYPE.MARKET:
if self.holding_order.applSeqNum!=exec.BidApplSeqNum and self.holding_order.applSeqNum!=exec.OfferApplSeqNum:
self.WARN('MARKET order followed by unmatch exec, take as traded over!')
assert self.cage_type==CAGE.CYB, f'{self.SecurityID:06d} not CYB'
self.insertOrder(self.holding_order)
self.holding_nb = 0
self._useTimestamp(self.holding_order.TransactTime)
self.genSnap() #先出一个snap,时戳用市价单的
self._useTimestamp(exec.TransactTime)
if self.holding_nb!=0:
# 紧跟缓存单的成交
level_side = SIDE.ASK if exec.BidApplSeqNum==self.holding_order.applSeqNum else SIDE.BID #level_side:缓存单的对手盘
self.DBG(f'level_side={level_side}')
assert self.holding_order.qty>=exec.LastQty, f"{self.SecurityID:06d} holding order Qty unmatch"
if self.holding_order.qty==exec.LastQty:
self.holding_nb = 0
else:
self.holding_order.qty -= exec.LastQty
if self.holding_order.type==TYPE.MARKET: #修改市价单的价格
self.holding_order.price = exec.LastPx
self.holding_order.traded = True
if level_side==SIDE.ASK:
self.tradeLimit(SIDE.ASK, exec.LastQty, exec.OfferApplSeqNum)
else:
self.tradeLimit(SIDE.BID, exec.LastQty, exec.BidApplSeqNum)
if self.holding_nb!=0 and self.holding_order.type==TYPE.LIMIT: #检查限价单是否还有对手价
if (self.holding_order.side==SIDE.BID and (self.holding_order.price<self.ask_min_level_price or self.ask_min_level_qty==0)) or \
(self.holding_order.side==SIDE.ASK and (self.holding_order.price>self.bid_max_level_price or self.bid_max_level_qty==0)):
# 对手盘已空,缓存单入列
self.insertOrder(self.holding_order)
self.holding_nb = 0
if self.cage_type==CAGE.CYB:
self.enterCage()
if self.holding_nb==0:
self.genSnap() #缓存单成交完
elif self.bid_waiting_for_cage or self.ask_waiting_for_cage:
self.DBG("Order entered cage & exec.")
self.tradeLimit(SIDE.ASK, exec.LastQty, exec.OfferApplSeqNum)
self.tradeLimit(SIDE.BID, exec.LastQty, exec.BidApplSeqNum)
if self.cage_type==CAGE.CYB:
self.enterCage()
self.genSnap() #出一个snap
else:
assert self.holding_nb==0, f'{self.SecurityID:06d} unexpected exec while holding_nb!=0'
#20221010 300654 碰到深交所订单乱序:先发送2档以上的逐笔成交,再发送1档的撤单(卖方1档撤单导致买方订单进入价格笼子,吃掉卖方2档及以上);目前直接应用成交可以正常继续重建:
if not ((exec.TransactTime%SZSE_TICK_CUT==92500000)or(exec.TransactTime%SZSE_TICK_CUT==150000000) if self.SecurityIDSource==SecurityIDSource_SZSE else (exec.TransactTime==9250000)or(exec.TransactTime==15000000)) and\
self.TradingPhaseMarket!=axsbe_base.TPM.VolatilityBreaking:
self.WARN(f'unexpected exec @{exec.TransactTime}!')
self.tradeLimit(SIDE.ASK, exec.LastQty, exec.OfferApplSeqNum)
self.tradeLimit(SIDE.BID, exec.LastQty, exec.BidApplSeqNum)
if self.ask_min_level_qty==0 or self.bid_max_level_qty==0 or self.ask_min_level_price>self.bid_max_level_price:
self.INFO('openCall/closeCall trade over')
if self.TradingPhaseMarket==axsbe_base.TPM.VolatilityBreaking:
self.TradingPhaseMarket = exec.TransactTime
self.genSnap() #集合竞价所有成交完成
def enterCage(self):
'''判断订单是否可进入笼子,若进入笼子,判断是否可以成交'''
while True:
if self.bid_cage_upper_ex_min_level_qty and self.bid_cage_upper_ex_min_level_price<=CYB_cage_upper(self.bid_cage_ref_px): #买方隐藏订单可以进入笼子
if self.ask_min_level_qty and self.bid_cage_upper_ex_min_level_price>=self.ask_min_level_price: #可与卖方最优成交
self.DBG('ASK px may changed: waiting for BID order to enter cage & exec')
break
else: #无法成交,将隐藏订单加到买方队列
self.bid_max_level_price = self.bid_cage_upper_ex_min_level_price
self.bid_max_level_qty = self.bid_cage_upper_ex_min_level_qty
self.BidWeightSize += self.bid_cage_upper_ex_min_level_qty
self.BidWeightValue += self.bid_cage_upper_ex_min_level_price * self.bid_cage_upper_ex_min_level_qty
self.DBG('BID order enter cage and became max level')
self.ask_cage_ref_px = self.bid_max_level_price
self.DBG(f'ASK cage ref px={self.ask_cage_ref_px}')
self.ask_waiting_for_cage = True if self.cage_type==CAGE.CYB else False #买方最优价被修改,则判断卖方隐藏订单
#下一个隐藏订单,继续循环,直到无隐藏订单、隐藏订单可成交
self.bid_cage_upper_ex_min_level_qty = 0
for p, l in sorted(self.bid_level_tree.items(),key=lambda x:x[0], reverse=False): #从小到大遍历
if p>self.bid_cage_upper_ex_min_level_price:
self.bid_cage_upper_ex_min_level_price = p
self.bid_cage_upper_ex_min_level_qty = l.qty
self.DBG(f'Refresh bid_cage_upper_ex_min_level_price={self.bid_cage_upper_ex_min_level_price} by prev bid level enter cage')
break
else:
self.bid_waiting_for_cage = False
if self.ask_cage_lower_ex_max_level_qty and self.ask_cage_lower_ex_max_level_price>=CYB_cage_lower(self.ask_cage_ref_px): #卖方隐藏订单可以进入笼子
if self.bid_max_level_qty and self.ask_cage_lower_ex_max_level_price<=self.bid_max_level_price: #可与买方最优成交
self.DBG('BID px may changed: waiting for ASK order to enter cage & exec')
break
else: #无法成交,将隐藏订单加到买方队列
self.ask_min_level_price = self.ask_cage_lower_ex_max_level_price
self.ask_min_level_qty = self.ask_cage_lower_ex_max_level_qty
self.AskWeightSize += self.ask_cage_lower_ex_max_level_qty
self.AskWeightValue += self.ask_cage_lower_ex_max_level_price * self.ask_cage_lower_ex_max_level_qty
self.DBG('ASK order enter cage and became min level')
self.bid_cage_ref_px = self.ask_min_level_price
self.DBG(f'BID cage ref px={self.bid_cage_ref_px}')
self.bid_waiting_for_cage = True if self.cage_type==CAGE.CYB else False #卖方最优价被修改,则判断买方隐藏订单
self.ask_cage_lower_ex_max_level_qty = 0
for p, l in sorted(self.ask_level_tree.items(),key=lambda x:x[0], reverse=True): #从大到小遍历