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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! MD/TD 双会话纯状态机(逐字对照原稿 `CtpMdApi` 243-410 与 `CtpTdApi` 411-892)。
//!
//! 设计:
//! - **`step` 单步语义**:输入一个回报事件、输出一个动作/事件向量;零线程、
//! 零时钟、零 sleep —— 原稿的 `while+sleep` 流控重试与 `EventEngine` 定时器
//! 都归上层(DESIGN.md D-FLCN/D-TIME)。
//! - **合约表共享**:原稿的模块级 `symbol_contract_map` 在这里 = 注入的
//! `Contracts` 共享表(`Arc<Mutex<HashMap<String, ContractData>>>`),
//! 由插件层创建并分发给 MD/TD 两台机。
//! - 持仓合并、order/trade 缓冲、sysid 映射、动态查询轮转全部按原稿逐字移植。
use crate::map::{self, Mapped};
use crate::wire::{
DepthMarketData, ErrorField, InputOrder, InputOrderAction, InstrumentCommissionRateField,
InstrumentField, InstrumentMarginRateField, InstrumentStatusField, InvestorPositionField,
OrderField, TradeField, TradingAccountField,
};
use ek_data::constant::{Direction, Offset, OrderType, Status};
use ek_data::log::{LEVEL_ERROR, LEVEL_INFO, LogData};
use ek_data::{
AccountData, CancelRequest, ContractData, OrderData, OrderRequest, PositionData, TickData,
TradeData,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use ek_data::log::LEVEL_WARNING;
/// 合约共享表(原稿全局 `symbol_contract_map` 的进程内等价物)。
pub type Contracts = Arc<Mutex<HashMap<String, ContractData>>>;
/// 空合约表构造。
pub fn contracts_empty() -> Contracts {
Arc::new(Mutex::new(HashMap::new()))
}
// ================ 日志 helper(等价原稿 gateway.write_log/write_error) ================
/// info 级日志。
pub fn log_info(gw: &str, msg: impl Into<String>) -> LogData {
LogData {
gateway_name: gw.to_string(),
msg: msg.into(),
level: LEVEL_INFO,
}
}
/// error 级日志(错误行自动拼"代码/信息",原稿 write_error 216-222)。
pub fn log_error_with(api_msg: &str, gw: &str, e: &ErrorField) -> LogData {
LogData {
gateway_name: gw.to_string(),
msg: map::error_text(api_msg, e),
level: LEVEL_ERROR,
}
}
// ================ MD 行情会话(原稿 CtpMdApi) ================
/// MD 会话配置(原稿 `CtpMdApi.connect` 入参)。
#[derive(Debug, Clone, Default)]
pub struct MdConfig {
/// 行情前置地址(原稿 connect 已补完 "tcp://" 前缀后传入)
pub addr: String,
/// 用户代码(行情登录用)
pub user: String,
/// 密码
pub password: String,
/// 经纪公司代码
pub broker: String,
}
/// MD 回报事件。
#[derive(Debug, Clone)]
/// MD 事件面(native 桥适配官方回报;mock 层直接喂值)。
///
/// Box 化:#[allow(clippy::large_enum_variant)] 之类抑损不是目标——本枚举
/// 只在适配线程步进,不做高频批量装箱,加 Box 反而破坏模式匹配直观性。
#[allow(clippy::large_enum_variant)]
pub enum MdEvent {
/// onFrontConnected(265)
FrontConnected,
/// onFrontDisconnected(reason)(270)
FrontDisconnected(i64),
/// onRspUserLogin(data, error)(275)
RspUserLogin {
/// None = 成功
error: Option<ErrorField>,
},
/// onRspError(288)
RspError(ErrorField),
/// onRspSubMarketData(292)
RspSubMarketData {
/// Some(err) = 订阅失败(error_id 非零;None 原稿 296 行两面皆静默)
error: Option<ErrorField>,
},
/// onRtnDepthMarketData(301)
RtnDepthMarketData(DepthMarketData),
}
/// MD 输出动作。
#[derive(Debug, Clone)]
/// MD 生产输出(unified 面:命令 → 传输;数据 → 总线)。
#[allow(clippy::large_enum_variant)]
pub enum MdOut {
/// 创建/连接行情 API(原稿 connect() 368-382;flow_path 供 levefile 行情流文件
/// 落位,原稿固定为 `{gateway_name}\Md`,native 层使用)
ReqConnect {
/// 行情前置地址
addr: String,
/// 流文件目录尾段
flow_path: String,
},
/// reqUserLogin(384-393)
ReqLogin {
/// 用户代码
user: String,
/// 密码
password: String,
/// 经纪公司代码
broker: String,
},
/// subscribeMarketData(395-399)
ReqSubscribe(Vec<String>),
/// 上抛行情(经 gateway.on_tick)
Tick(TickData),
/// 业务日志(带等级;ERROR = write_error 的形态)
Log(LogData),
}
/// MD 状态机。
pub struct MdDriver {
/// 网关名(日志与流文件路径的命名)
pub gw: String,
cfg: MdConfig,
contracts: Contracts,
/// 已登记的订阅集合(原稿 subscribed set;去重保序用等值判定)
subscribed: Vec<String>,
login_status: bool,
connect_status: bool,
/// 本地视角当日("YYYYMMDD";eTimer 刷新,原稿 update_date)
current_date: String,
}
impl MdDriver {
/// 构造(合约表注入;current_date 初值由调用方给定——原稿是 datetime.now()
/// 的本地日期,Rust 显式化以免隐性时钟)。
pub fn new(gw: &str, cfg: MdConfig, contracts: Contracts, current_date: String) -> Self {
Self {
gw: gw.to_string(),
cfg,
contracts,
subscribed: Vec::new(),
login_status: false,
connect_status: false,
current_date,
}
}
/// eTimer 秒级刷新当日(原稿 gateway.process_timer_event 235 行调 md.update_date)。
pub fn update_date(&mut self, date: String) {
self.current_date = date;
}
/// 行情订阅入口(原稿 gateway.subscribe → md.subscribe 191-193/395-399;
/// 登录前只登记,登录后立即发起)。
pub fn subscribe(&mut self, symbol: &str) -> Vec<MdOut> {
if !self.subscribed.iter().any(|s| s == symbol) {
self.subscribed.push(symbol.to_string());
}
if self.login_status {
vec![MdOut::ReqSubscribe(vec![symbol.to_string()])]
} else {
Vec::new()
}
}
/// 连接(原稿 MD connect 368-382):首次 → 发 ReqConnect;重复调用守卫静默。
/// close 守卫面由 `connect_status()` getter 提供(原稿 401-404)。
pub fn connect(&mut self) -> Vec<MdOut> {
if self.connect_status {
return Vec::new();
}
self.connect_status = true;
vec![MdOut::ReqConnect {
addr: self.cfg.addr.clone(),
flow_path: format!("{}\\Md", self.gw),
}]
}
/// 换配置并复位连接/登录守卫(0.3.0 configure 面;订阅集保留 —— 登录后
/// RspUserLogin 重订阅链自会把新订阅推下去)。
pub fn reconfigure(&mut self, cfg: MdConfig) {
self.cfg = cfg;
self.connect_status = false;
self.login_status = false;
}
/// 步进(原型 CtpMdApi 各回调)。
pub fn step(&mut self, ev: MdEvent) -> Vec<MdOut> {
match ev {
MdEvent::FrontConnected => {
self.connect_status = true;
vec![
MdOut::Log(log_info(&self.gw, "行情服务器连接成功")),
MdOut::ReqLogin {
user: self.cfg.user.clone(),
password: self.cfg.password.clone(),
broker: self.cfg.broker.clone(),
},
]
}
MdEvent::FrontDisconnected(reason) => {
self.login_status = false;
vec![MdOut::Log(log_info(
&self.gw,
format!("行情服务器连接断开,原因{reason}"),
))]
}
MdEvent::RspUserLogin { error } => match error {
None => {
self.login_status = true;
let mut outs = vec![MdOut::Log(log_info(&self.gw, "行情服务器登录成功"))];
if !self.subscribed.is_empty() {
outs.push(MdOut::ReqSubscribe(self.subscribed.clone()));
}
outs
}
Some(e) => vec![MdOut::Log(log_error_with(
"行情服务器登录失败",
&self.gw,
&e,
))],
},
MdEvent::RspError(e) => vec![MdOut::Log(log_error_with("行情接口报错", &self.gw, &e))],
MdEvent::RspSubMarketData { error } => match error {
Some(e) => vec![MdOut::Log(log_error_with("行情订阅失败", &self.gw, &e))],
None => Vec::new(),
},
MdEvent::RtnDepthMarketData(dm) => {
// 合约未收录 → 静默丢(301-311)
let contract = {
let m = self.contracts.lock().unwrap();
m.get(&dm.instrument_id).cloned()
};
match map::tick_from(&dm, contract.as_ref(), &self.gw, &self.current_date) {
Mapped::Ok(t) => vec![MdOut::Tick(t)],
Mapped::Skip(_) => Vec::new(),
}
}
}
}
}
// ================ TD 交易会话(原稿 CtpTdApi) ================
/// TD 会话配置(原稿 `CtpTdApi.connect` 749-777 入参)。
#[derive(Debug, Clone, Default)]
pub struct TdConfig {
/// 交易前置地址
pub addr: String,
/// 用户代码
pub user: String,
/// 密码
pub password: String,
/// 经纪公司代码
pub broker: String,
/// 授权编码(空则跳过认证直连登录,原稿 448-451)
pub auth_code: String,
/// 产品名称(AppID,认证用)
pub app_id: String,
/// 收录的产品类白名单(D-PC-FILTER;空 = 回落默认「期货」)。
/// 查询侧不过滤,收录侧按它严格丢弃(不进表、不上抛)。
pub product_classes: map::ProductClasses,
}
/// TD 回报事件。
#[derive(Debug, Clone)]
pub enum TdEvent {
/// onFrontConnected(445)
FrontConnected,
/// onFrontDisconnected(reason)(453)
FrontDisconnected(i64),
/// onRspAuthenticate(458-472)
RspAuthenticate {
/// None = 成功
error: Option<ErrorField>,
},
/// onRspUserLogin(474-490)
RspUserLogin {
/// None = 成功
error: Option<ErrorField>,
/// FrontID(仅成功时有意义,原稿取 data["FrontID"])
front_id: i64,
/// SessionID
session_id: i64,
},
/// onRspSettlementInfoConfirm(519-533)
RspSettlementInfoConfirm {
/// None = 成功
error: Option<ErrorField>,
},
/// onRspQryInstrument(614-667)
RspQryInstrument {
/// 是否本包最后一笔
last: bool,
/// 数据行(错误包时 None)
row: Option<InstrumentField>,
},
/// onRspQryInvestorPosition(535-595)
RspQryInvestorPosition {
/// 是否本包最后一笔
last: bool,
/// 数据行
row: Option<InvestorPositionField>,
},
/// onRspQryTradingAccount(597-612)
RspQryTradingAccount {
/// 是否本包最后一笔
last: bool,
/// 数据行
row: Option<TradingAccountField>,
},
/// onRspOrderInsert(492-513)。原稿从 err 包 OrderRef/Direction/LimitPrice 等
/// 字段重造 REJECTED 单。
RspOrderInsert {
/// None = 成功受理(原稿只在 error 分支造单)
error: Option<ErrorField>,
/// 触发失败的报单原字段(transport 层随错误回报回带)
req: Option<InputOrder>,
},
/// onRspOrderAction(515-517)
RspOrderAction {
/// None = 成功
error: Option<ErrorField>,
},
/// onRtnOrder(669-718)
RtnOrder(OrderField),
/// onRtnTrade(720-747)
RtnTrade(TradeField),
// ---- 附加接口面(超出原稿):保证金率/手续费率/交易状态 ----
/// onRspQryInstrumentMarginRate。原稿无此路径 —— 端口按设计记录进 eLog
/// (不新增事件实体,记档见 DESIGN)。
RspQryInstrumentMarginRate {
/// 数据行
row: Option<InstrumentMarginRateField>,
/// 查询错误(超出设计错误面:查询没就绪等)
error: Option<ErrorField>,
/// 是否本包最后一笔
last: bool,
},
/// onRspQryInstrumentCommissionRate。原稿无此路径 —— 同上,记录进 eLog。
RspQryInstrumentCommissionRate {
/// 数据行
row: Option<InstrumentCommissionRateField>,
/// 查询错误
error: Option<ErrorField>,
/// 是否本包最后一笔
last: bool,
},
/// onRtnInstrumentStatus(纯被动推送;SDK 6.7.7 无对应 Req)。原稿无此路径。
RtnInstrumentStatus(InstrumentStatusField),
}
/// TD 输出动作。
#[derive(Debug, Clone)]
pub enum TdOut {
/// 创建/连接交易 API(779 前流程:connect() 749-777)
ReqConnect {
/// 交易前置地址
addr: String,
/// 流文件目录尾段(`{gateway_name}\Td`)
flow_path: String,
},
/// reqAuthenticate(779-792)
ReqAuthenticate {
/// 用户代码
user: String,
/// 经纪公司代码
broker: String,
/// 授权编码
auth_code: String,
/// 产品名称(AppID)
app_id: String,
},
/// reqUserLogin(794-806)
ReqLogin {
/// 用户代码
user: String,
/// 密码
password: String,
/// 经纪公司代码
broker: String,
},
/// reqSettlementInfoConfirm(482-485)
ReqSettlementConfirm {
/// 经纪公司代码
broker: String,
/// 用户代码
user: String,
},
/// reqQryInstrument(合约流控重试在 transport 层,DESIGN.md D-FLCN)
ReqQryInstrument,
/// reqQryTradingAccount(874-877)
ReqQryAccount {
/// 经纪公司代码
broker: String,
/// 用户代码
user: String,
},
/// reqQryInvestorPosition(879-887)
ReqQryPosition {
/// 经纪公司代码
broker: String,
/// 用户代码
user: String,
},
/// reqOrderInsert(820-845 成功路径)
Insert(InputOrder),
/// reqOrderAction(856-872 成功路径)
Cancel(InputOrderAction),
/// 上抛合约(仅期货;经 gateway.on_contract 652)
Contract(ContractData),
/// 上抛订单(经 gateway.on_order)
Order(OrderData),
/// 上抛成交(经 gateway.on_trade)
Trade(TradeData),
/// 上抛持仓(合并完成;经 gateway.on_position 589-590)
Position(PositionData),
/// 持仓查询完成(原稿 593 行 EVENT_POSITION_QUERY_DONE;对齐 ek-oms 相位门)
PositionQueryDone(String),
/// 合约收齐(原稿 659 → BaseGateway.on_contract_finish → EVENT_CONTRACT_FINISH
/// = "eContractFinish" 全局线、无 gw 后缀;载荷给网关名以便多网关辨源,D-CFIN)
ContractFinish(String),
/// 上抛账户(612)
Account(AccountData),
/// 业务日志
Log(LogData),
}
/// 持仓 accumulator(键 = 合约 + 持仓方向码,原稿 548 的 dict key 形态)。
struct PositionAccum {
pos: PositionData,
}
/// TD 状态机。
pub struct TdDriver {
gw: String,
cfg: TdConfig,
contracts: Contracts,
/// 请求计数(原稿 reqid;native 层使用)
pub reqid: i64,
/// 本地报单号计数(原稿 order_ref)
order_ref: i64,
/// 已连接/已登录/已认证/认证失败/登录失败/合约已收齐
connect_status: bool,
login_status: bool,
auth_status: bool,
auth_failed: bool,
login_failed: bool,
contract_inited: bool,
/// FrontID(登录回报)
front_id: i64,
/// SessionID
session_id: i64,
/// 认证流程标志(驱动机;MERGED: auth 独立状态)
/// 持仓合并缓存(原稿 positions dict;_TH 初始化面)
positions: HashMap<String, PositionAccum>,
/// 合约未齐时的订单缓冲(原稿 order_data;661-662)
order_buf: Vec<OrderField>,
/// 合约未齐时的成交缓冲(原稿 trade_data;665-667)
trade_buf: Vec<TradeField>,
/// OrderSysID → 本地委托号表(原稿 sysid_orderid_map;718)
sysid_orderid: HashMap<String, String>,
/// 查询轮转标志:[false=资金, true=持仓](原稿 query_functions 列表轮换)
next_pos: bool,
/// 交易状态推送去重键(exchange|instrument|status|segment)。
/// 公流重放整批重推会话快照,不去重会把 eLog 冲成几百行(D-NATIVE-EXTRA-3);
/// 键不含 enter_time —— 快照重放同状态的多变进入时刻不重记。
status_seen: std::collections::HashSet<String>,
/// 合约阶段计数(D-PC-FILTER;收尾时汇总成一条日志,不逐行刷):
/// 收录 / 按勾选丢弃 / 勾选了但本数据面映射不了。
contract_kept: usize,
contract_filtered: usize,
contract_unmapped: usize,
/// 未映射的产品类码集合。汇总里必须把码列出来 —— 原来逐行日志会给码,
/// 改成汇总之后如果把码丢了,「未映射 3」就是个查不出原因的数字。
contract_unmapped_codes: std::collections::BTreeSet<String>,
/// 归一化后的勾选表(在 new/reconfigure 各算一次)。不在每行合约上重算 ——
/// 全量一发 2226 行,逐行 `normalize()` 就是 2226 次排序+分配。
accepted: Vec<String>,
/// 已提示过「合约被网关过滤」的合约代码(回报侧去重:同一合约只提示一次)。
filtered_report_seen: std::collections::HashSet<String>,
}
impl TdDriver {
/// 构造。
pub fn new(gw: &str, cfg: TdConfig, contracts: Contracts) -> Self {
// 归一化只在这里与 reconfigure 各算一次(cfg 随后被 move 进结构体)。
let accepted = cfg.product_classes.normalize();
Self {
gw: gw.to_string(),
cfg,
contracts,
reqid: 0,
order_ref: 0,
connect_status: false,
login_status: false,
auth_status: false,
auth_failed: false,
login_failed: false,
contract_inited: false,
front_id: 0,
session_id: 0,
positions: HashMap::new(),
order_buf: Vec::new(),
trade_buf: Vec::new(),
sysid_orderid: HashMap::new(),
next_pos: false,
status_seen: std::collections::HashSet::new(),
contract_kept: 0,
contract_filtered: 0,
contract_unmapped: 0,
contract_unmapped_codes: std::collections::BTreeSet::new(),
accepted,
filtered_report_seen: std::collections::HashSet::new(),
}
}
/// 本地委托号段(front_session_ref 三段下划线,原稿 495/681/850)。
pub fn local_orderid(&self, order_ref: &str) -> String {
format!("{}_{}_{}", self.front_id, self.session_id, order_ref)
}
/// 认证失败标志(63 错;原稿 auth_failed 781-782 由 authenticate 的守卫读)。
pub fn auth_failed(&self) -> bool {
self.auth_failed
}
/// 当前生效的产品类白名单(已归一化;供回包/界面显示)。
pub fn product_classes(&self) -> Vec<String> {
self.accepted.clone()
}
/// 合约阶段计数快照 `(收录, 按勾选丢弃, 未映射)`(测试与日志核对用)。
pub fn contract_counts(&self) -> (usize, usize, usize) {
(
self.contract_kept,
self.contract_filtered,
self.contract_unmapped,
)
}
/// 合约被网关勾选过滤之后的回报处理(D-PC-FILTER)。
///
/// 级别从 `LEVEL_ERROR` 降为 `LEVEL_WARNING`:这是我们自己的勾选产生的预期结果,
/// 不是故障;并且**同一合约只提示一次**(委托/成交回报会重放,逐行刷会把 eLog
/// 冲成几百行,与 `status_seen` 那条 D-NATIVE-EXTRA-3 是同一个道理)。
fn filtered_contract_log(&mut self, symbol: &str, kind: &str) -> Vec<TdOut> {
if !self.filtered_report_seen.insert(symbol.to_string()) {
return Vec::new();
}
vec![TdOut::Log(LogData {
gateway_name: self.gw.clone(),
msg: format!("{kind}回报缺少在册合约:{symbol}(该合约已被网关产品类勾选过滤)"),
level: LEVEL_WARNING,
})]
}
/// 登录态(适配层复接用)。
pub fn login_status(&self) -> bool {
self.login_status
}
/// 登录失败标志(原稿 796-797 的 login 守卫,登录失败不再续发;适配层用)。
pub fn login_failed(&self) -> bool {
self.login_failed
}
/// 合约收齐标志(适配层复接用)。
pub fn contract_inited(&self) -> bool {
self.contract_inited
}
/// 当前持仓合并缓存键数(测试/适配复接用)。
pub fn positions_len(&self) -> usize {
self.positions.len()
}
/// FrontID(登录回报;适配层使用)。
pub fn front_id(&self) -> i64 {
self.front_id
}
/// 连接态(原稿 close 401-404 / 889-892 的 `if connect_status: exit()` 守卫,适配层用)。
pub fn connect_status(&self) -> bool {
self.connect_status
}
/// SessionID。
pub fn session_id(&self) -> i64 {
self.session_id
}
/// 已本地报单计数(order_ref;适配层使用)。
pub fn order_ref(&self) -> i64 {
self.order_ref
}
/// 发单(原稿 send_order 808-854)。 Returns 输出动作 + en_orderid。
/// 校验路径原样(missings log + `""`):开平/类型缺者不放行;
/// 方向 miss(NET)→ 空报单方向(原稿 get(...,"") 行为)。
pub fn send_order(&mut self, req: &OrderRequest) -> SendOutcome {
let Some(offset_code) = map::offset_to(req.offset) else {
return SendOutcome::rejected(log_info(&self.gw, "请选择开平方向"));
};
let Some((price_type, time_cond, vol_cond)) = map::order_type_to(req.order_type) else {
return SendOutcome::rejected(log_info(
&self.gw,
format!("当前接口不支持该类型的委托{}", req.order_type.as_str()),
));
};
self.order_ref += 1;
let order_ref = format!("{}", self.order_ref);
let input = InputOrder {
instrument_id: req.symbol.clone(),
exchange_id: req.exchange.as_str().to_string(),
limit_price: req.price,
volume_total_original: req.volume as i64,
order_price_type: price_type.to_string(),
direction: map::direction_to(req.direction).unwrap_or("").to_string(),
comb_offset_flag: offset_code.to_string(),
order_ref: order_ref.clone(),
investor_id: self.cfg.user.clone(),
user_id: self.cfg.user.clone(),
broker_id: self.cfg.broker.clone(),
// 830-841 固定面:投机/立即触发/非强平/不自动挂起/最小量 1
comb_hedge_flag: "1".to_string(),
contingent_condition: "1".to_string(),
force_close_reason: "0".to_string(),
is_auto_suspend: 0,
time_condition: time_cond.to_string(),
volume_condition: vol_cond.to_string(),
min_volume: 1,
};
let orderid = self.local_orderid(&order_ref);
// 原稿 850-852:回 SUBMITTING 单在 reqOrderInsert 送出(返回码 0)之后;
// 返回码 n 的判定归传输层(0.1.0 由 plugin 按 trait 返回值裁决),
// 这里只顺序产出插单命令 + SUBMITTING 单回报。
let outs = vec![
TdOut::Insert(input),
TdOut::Order(req.create_order_data(&orderid, &self.gw)),
];
SendOutcome::placed(outs, format!("{}.{}", self.gw, orderid))
}
/// 流文件目录(原稿 createFtdcTraderApi 767:`{gateway_name}\\Td`)。
pub fn flow_path(&self) -> String {
format!("{}\\Td", self.gw)
}
/// 连接(原稿 TD connect 763-777):首次 → 发 ReqConnect;**重复调用 →
/// authenticate()**(含 auth_failed 守卫)。close 守卫面由 `connect_status()`
/// getter 提供给适配层(原稿 889-892)。
pub fn connect(&mut self) -> Vec<TdOut> {
if self.connect_status {
return self.authenticate();
}
self.connect_status = true;
vec![TdOut::ReqConnect {
addr: self.cfg.addr.clone(),
flow_path: self.flow_path(),
}]
}
/// 换配置并复位连接/认证/登录/合约守卫(0.3.0 configure 面;错密改密
/// 再连的正路)。持仓/订单缓存保留(交易所侧会重报);**TD 侧有地址时共享合约表清空**
/// (0.6.0,D-PC-FILTER —— 勾选收窄必须真生效,configure 本就重走全量查询;
/// MD-only 配置不清,因为没有任何东西会把表重新灌满)。
pub fn reconfigure(&mut self, cfg: TdConfig) {
self.cfg = cfg;
self.connect_status = false;
self.login_status = false;
self.auth_status = false;
self.auth_failed = false;
self.login_failed = false;
self.contract_inited = false;
// 勾选可在运行时改,旧会话的计数与「已提示过」的合约都不能带进新会话。
self.contract_kept = 0;
self.contract_filtered = 0;
self.contract_unmapped = 0;
self.contract_unmapped_codes.clear();
self.accepted = self.cfg.product_classes.normalize();
self.filtered_report_seen.clear();
// D-PC-FILTER:勾选可在运行时收窄,但 configure 已是「断开重连 + 全量重查」
// (0.5.0 语义),旧会话灌进来的合约必须清,否则收窄只对之后新收录的合约生效 ——
// 先勾期权再改回只期货,期权合约还留在表里,它的 tick/持仓/回报照样并库。
// 代价写明:清表到新一轮合约查询收尾之间,已订阅标的的 tick 会因缺合约被丢。
//
// 守卫:**只在 TD 真会重走全量查询时清**。td addr 为空 = MD-only configure,
// 没有任何东西会把表重新灌满,清了等于把所有 tick 并库永久掐死 —— 改动前旧表
// 还在,MD-only 至少还能吃到上一轮的合约。这是清表引入的第一条边界。
if !self.cfg.addr.is_empty() {
self.contracts.lock().unwrap().clear();
}
}
/// 认证(原稿 779-792;auth_failed 守卫 781-782 静默不重发)。
pub fn authenticate(&mut self) -> Vec<TdOut> {
if self.auth_failed {
return Vec::new();
}
vec![TdOut::ReqAuthenticate {
user: self.cfg.user.clone(),
broker: self.cfg.broker.clone(),
auth_code: self.cfg.auth_code.clone(),
app_id: self.cfg.app_id.clone(),
}]
}
/// 登录(原稿 794-806;login_failed 守卫 796-797 静默不重发)。
pub fn login(&mut self) -> Vec<TdOut> {
if self.login_failed {
return Vec::new();
}
vec![TdOut::ReqLogin {
user: self.cfg.user.clone(),
password: self.cfg.password.clone(),
broker: self.cfg.broker.clone(),
}]
}
/// 撤单(原稿 cancel_order 856-872;订单号三段解析失败 → log + 放行,
/// D6:原稿 int() 会抛 ValueError,Rust 转错误日记 + 静默)。
pub fn cancel_order(&mut self, req: &CancelRequest) -> Vec<TdOut> {
match map::cancel_action_from(
&req.orderid,
&req.symbol,
req.exchange,
&self.cfg.broker,
&self.cfg.user,
) {
Some(action) => vec![TdOut::Cancel(action)],
None => vec![TdOut::Log(log_info(
&self.gw,
format!("撤单请求委托号异常:{}", req.orderid),
))],
}
}
/// 订单成功发光后登记 sysid 报表(707,原稿 718)。
fn remember_sysid(&mut self, sysid: &str, orderid: &str) {
self.sysid_orderid
.insert(sysid.to_string(), orderid.to_string());
}
/// 查询轮转(原稿 CtpGateway.process_timer_event 224-239 + query_* 874-887;
/// 计数器由驱动独立持有,轮转次序 = 资金 → 持仓 → 资金 …)。
pub fn on_timer(&mut self) -> Vec<TdOut> {
if self.next_pos {
self.next_pos = false;
if self.contracts.lock().unwrap().is_empty() {
// 原稿 881-882:合约表为空 → 跳过持仓查询
return Vec::new();
}
vec![TdOut::ReqQryPosition {
broker: self.cfg.broker.clone(),
user: self.cfg.user.clone(),
}]
} else {
self.next_pos = true;
vec![TdOut::ReqQryAccount {
broker: self.cfg.broker.clone(),
user: self.cfg.user.clone(),
}]
}
}
/// 步进(原型 CtpTdApi 各回调)。
pub fn step(&mut self, ev: TdEvent) -> Vec<TdOut> {
match ev {
TdEvent::FrontConnected => {
self.connect_status = true;
let mut outs = vec![TdOut::Log(log_info(&self.gw, "交易服务器连接成功"))];
// 原稿 448-451:auth_code 空 → 直登
if self.cfg.auth_code.is_empty() {
outs.extend(self.login());
} else {
outs.extend(self.authenticate());
}
outs
}
TdEvent::FrontDisconnected(reason) => {
self.login_status = false;
vec![TdOut::Log(log_info(
&self.gw,
format!("交易服务器连接断开,原因{reason}"),
))]
}
TdEvent::RspAuthenticate { error } => match error {
None => {
self.auth_status = true;
vec![
TdOut::Log(log_info(&self.gw, "交易服务器授权验证成功")),
TdOut::ReqLogin {
user: self.cfg.user.clone(),
password: self.cfg.password.clone(),
broker: self.cfg.broker.clone(),
},
]
}
Some(e) => {
let outs = vec![TdOut::Log(log_error_with(
"交易服务器授权验证失败",
&self.gw,
&e,
))];
if e.error_id == 63 {
self.auth_failed = true;
}
outs
}
},
TdEvent::RspUserLogin {
error,
front_id,
session_id,
} => match error {
None => {
self.front_id = front_id;
self.session_id = session_id;
self.login_status = true;
vec![
TdOut::Log(log_info(&self.gw, "交易服务器登录成功")),
TdOut::ReqSettlementConfirm {
broker: self.cfg.broker.clone(),
user: self.cfg.user.clone(),
},
]
}
Some(e) => {
self.login_failed = true;
vec![TdOut::Log(log_error_with(
"交易服务器登录失败",
&self.gw,
&e,
))]
}
},
TdEvent::RspSettlementInfoConfirm { error: _ } => {
// 原稿 523:无条件写 log;流控重试归 transport 层(D-FLCN)
// 新一轮合约查询开始:计数复位(收尾汇总的基准必须是本轮)。
self.contract_kept = 0;
self.contract_filtered = 0;
self.contract_unmapped = 0;
self.contract_unmapped_codes.clear();
// 新一轮登录 → 合约表会重新灌满,上一轮「已提示过」的合约必须重来,
// 否则第二轮会话里被过滤的合约连一条提示都不会有。
self.filtered_report_seen.clear();
vec![
TdOut::Log(log_info(&self.gw, "结算信息确认成功")),
TdOut::ReqQryInstrument,
]
}
TdEvent::RspQryInstrument { last, row } => {
let mut outs = Vec::new();
if let Some(inf) = row {
// D-PC-FILTER:先勾选、再 map,同一行只计一次(否则「未勾选」与
// 「未映射」会重复计数,收尾汇总就是假的)。
// 不在勾选内 → 静默丢弃:不进共享表、不上抛、不逐行发日志。
if !self.accepted.iter().any(|c| c == &inf.product_class) {
self.contract_filtered += 1;
} else {
match map::contract_from(&inf, &self.gw) {
Mapped::Ok(c) => {
// 勾选即收录 + 上抛(取代原稿「全表收录、仅期货上抛」的硬编码)
self.contracts
.lock()
.unwrap()
.insert(c.symbol.clone(), c.clone());
self.contract_kept += 1;
outs.push(TdOut::Contract(c.clone()));
}
// 勾选了但本数据面映射不了(组合 '3'、现货 '4' 等):只计数 + 记码。
// 逐行 WARNING 会刷上千条,汇总在收尾那一条里。
Mapped::Skip(_) => {
self.contract_unmapped += 1;
self.contract_unmapped_codes
.insert(inf.product_class.clone());
}
}
}
}
if last {
self.contract_inited = true;
let unmapped_codes = if self.contract_unmapped_codes.is_empty() {
String::new()
} else {
format!(
"(码:{})",
self.contract_unmapped_codes
.iter()
.cloned()
.collect::<Vec<_>>()
.join(",")
)
};
outs.push(TdOut::Log(log_info(
&self.gw,
format!(
"合约信息查询成功:收录 {} / 按勾选丢弃 {} / 未映射 {}{unmapped_codes}(收录产品类:{})",
self.contract_kept,
self.contract_filtered,
self.contract_unmapped,
self.accepted.join(" ")
),
)));
outs.push(TdOut::ContractFinish(self.gw.clone()));
let buffered_orders = std::mem::take(&mut self.order_buf);
for data in buffered_orders {
let mut sub = self.step(TdEvent::RtnOrder(data.clone()));
outs.append(&mut sub);
}
let buffered_trades = std::mem::take(&mut self.trade_buf);
for data in buffered_trades {
let mut sub = self.step(TdEvent::RtnTrade(data.clone()));
outs.append(&mut sub);
}
}
outs
}
TdEvent::RspQryInvestorPosition { last, row } => {
// 原稿 539-540:data 缺 → 直接 return(空持仓查询不发事件、
// 不冲刷、连 PositionDone 都不发;0 行与多行的末包均带 last)
let Some(row) = row else { return Vec::new() };
let mut outs = Vec::new();
{
let contract = {
let m = self.contracts.lock().unwrap();
m.get(&row.instrument_id).cloned()
};
// 合约未收录 → 上层无库可并(原稿 543-546 同面)
if let Some(contract) = contract {
let key = format!("{}:{}", row.instrument_id, row.posi_direction);
let direction = map::direction_from(&row.posi_direction);
if !self.positions.contains_key(&key) {
let pos = map::new_position_data(
&row.instrument_id,
contract.exchange,
direction,
&self.gw,
)
.unwrap_or_default();
self.positions.insert(key.clone(), PositionAccum { pos });
}
let entry = self.positions.get_mut(&key).expect("just inserted");
map::accumulate_position(
&row,
&mut entry.pos,
contract.exchange,
contract.size,
);
} else {
// D-PC-FILTER:该合约被网关勾选过滤 → 持仓无法并库。
// 原稿这里是静默(543-546);补一条去重 WARNING,
// 免得期权持仓消失得毫无痕迹。
outs.extend(self.filtered_contract_log(&row.instrument_id, "持仓"));
}
if last {
let done = self
.positions
.values()
.map(|p| p.pos.clone())
.collect::<Vec<_>>();
for pos in done {
outs.push(TdOut::Position(pos));
}
outs.push(TdOut::PositionQueryDone(self.gw.clone()));
self.positions.clear();
}
}
outs
}
TdEvent::RspQryTradingAccount { last: _, row } => match row {
Some(ta) => vec![TdOut::Account(map::account_from(&ta, &self.gw))],
None => Vec::new(),
},
TdEvent::RspOrderInsert { error, req } => match (error, req) {
(Some(e), Some(input)) => {
let mut outs = vec![TdOut::Log(log_error_with("交易委托失败", &self.gw, &e))];
let contract = {
let m = self.contracts.lock().unwrap();
m.get(&input.instrument_id).cloned()
};
if let Some(contract) = contract {
let orderid = self.local_orderid(&input.order_ref);
let direction = map::direction_from(&input.direction);
let offset =
map::offset_from(&input.comb_offset_flag).unwrap_or(Offset::NONE);
outs.push(TdOut::Order(OrderData {
gateway_name: self.gw.clone(),
symbol: contract.symbol.clone(),
exchange: contract.exchange,
orderid,
order_type: OrderType::LIMIT,
direction: Some(direction.unwrap_or(Direction::NET)),
offset,
price: input.limit_price,
volume: input.volume_total_original as f64,
status: Status::REJECTED,
..OrderData::default()
}));
}
outs
}
_ => Vec::new(),
},
TdEvent::RspOrderAction { error } => match error {
Some(e) => vec![TdOut::Log(log_error_with("交易撤单失败", &self.gw, &e))],
None => Vec::new(),
},
TdEvent::RtnOrder(of) => {
if !self.contract_inited {
self.order_buf.push(of);
return Vec::new();
}
let contract = {
let m = self.contracts.lock().unwrap();
m.get(&of.instrument_id).cloned()
};
let Some(contract) = contract else {
// 原稿 676 直接索引(KeyError 面)→ 结构化丢弃
// (D-PC-FILTER:降级 WARNING + 同一合约只提示一次)
return self.filtered_contract_log(&of.instrument_id, "委托");
};
match map::order_from(&of, &contract, &self.gw) {
Mapped::Ok(order) => {
let orderid = order.orderid.clone();
let outs = vec![TdOut::Order(order)];
self.remember_sysid(&of.order_sys_id, &orderid);
outs
}
Mapped::Skip(reason) => vec![TdOut::Log(log_info(&self.gw, reason))],
}
}
TdEvent::RtnTrade(tf) => {
if !self.contract_inited {
self.trade_buf.push(tf);
return Vec::new();
}
let contract = {
let m = self.contracts.lock().unwrap();
m.get(&tf.instrument_id).cloned()
};
let Some(contract) = contract else {
// D-PC-FILTER:降级 WARNING + 同一合约只提示一次
return self.filtered_contract_log(&tf.instrument_id, "成交");
};
match self.sysid_orderid.get(&tf.order_sys_id) {
Some(orderid) => match map::trade_from(&tf, orderid, &contract, &self.gw) {
Mapped::Ok(trade) => vec![TdOut::Trade(trade)],
Mapped::Skip(reason) => vec![TdOut::Log(log_info(&self.gw, reason))],
},
None => vec![TdOut::Log(LogData {
gateway_name: self.gw.clone(),
msg: format!("成交回报缺少在册委托:{}", tf.order_sys_id),
level: LEVEL_ERROR,
})],
}
}
// ---- 附加接口面(超出原稿):三路只进 eLog,不新增事件实体 ----
TdEvent::RspQryInstrumentMarginRate { row, error, last } => {
let mut outs = Vec::new();
if let Some(e) = error {
outs.push(TdOut::Log(log_error_with("保证金率查询失败", &self.gw, &e)));
}
if let Some(r) = row {
if last {
outs.push(TdOut::Log(LogData {
gateway_name: self.gw.clone(),
msg: format!(
"保证金率(末包):{} {} 档 long {}/{} short {}/{} 相对交易所={}",
r.instrument_id,
r.hedge_flag,
r.long_margin_ratio_by_money,
r.long_margin_ratio_by_volume,
r.short_margin_ratio_by_money,
r.short_margin_ratio_by_volume,
r.is_relative,
),
level: LEVEL_INFO,
}));
}
} else if last {
outs.push(TdOut::Log(LogData {
gateway_name: self.gw.clone(),
msg: "保证金率查询:空结果(末包)".to_string(),
level: LEVEL_INFO,
}));
}
outs
}
TdEvent::RspQryInstrumentCommissionRate { row, error, last } => {
let mut outs = Vec::new();
if let Some(e) = error {
outs.push(TdOut::Log(log_error_with("手续费率查询失败", &self.gw, &e)));
}
if let Some(r) = row {
if last {
outs.push(TdOut::Log(LogData {
gateway_name: self.gw.clone(),
msg: format!(
"手续费率(末包):{} 开 {}/{} 平 {}/{} 平今 {}/{}",
r.instrument_id,
r.open_ratio_by_money,
r.open_ratio_by_volume,
r.close_ratio_by_money,
r.close_ratio_by_volume,
r.close_today_ratio_by_money,
r.close_today_ratio_by_volume,
),
level: LEVEL_INFO,
}));
}
} else if last {
outs.push(TdOut::Log(LogData {
gateway_name: self.gw.clone(),
msg: "手续费率查询:空结果(末包)".to_string(),
level: LEVEL_INFO,
}));
}
outs
}
TdEvent::RtnInstrumentStatus(s) => {
// 键不含 enter_time:公流重放的会话快照同状态常带不同进入时刻,
// 只在 (exchange, instrument, status, segment) 变化时显形一次。
let key = format!(
"{}|{}|{}|{}",
s.exchange_id, s.instrument_id, s.instrument_status, s.trading_segment_sn
);
if !self.status_seen.insert(key) {
return Vec::new();
}
vec![TdOut::Log(LogData {
gateway_name: self.gw.clone(),
msg: format!(
"交易状态:{}/{} status={} 进入 @{} (原因 {})",
s.exchange_id,
s.instrument_id,
s.instrument_status,
s.enter_time,
s.enter_reason
),
level: LEVEL_INFO,
})]
}
}
}
}
/// 发单结果(en_orderid = 成功路径;error 记拒绝 reason)。
pub struct SendOutcome {
/// 成功时的 en_orderid(全空 = 原稿返回 `""` 的形态)
pub en_orderid: String,
/// 拒绝时的 log(原稿 write_log 后返回 "")
pub error: Option<LogData>,
/// 插单前序(发起连接/认证/登录)动作
pub outs: Vec<TdOut>,
}
impl SendOutcome {
fn rejected(log: LogData) -> Self {
Self {
en_orderid: String::new(),
error: Some(log),
outs: Vec::new(),
}
}
fn placed(outs: Vec<TdOut>, en_orderid: String) -> Self {
Self {
en_orderid,
error: None,
outs,
}
}
}