ek-ctp 0.12.3

CTP gateway for the enkeep ek ecosystem: MD/TD session drivers mapping CTP wire rows onto ek-data objects over the ek-event bus (pure-logic core; the CTP SDK ships inside this package and native bridging lands behind the optional `native` feature).
Documentation
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
//! CTP 码值映射与 MySQL 时间换算(逐字对照 `enkeep_ctp/gateway/ctp_gateway.py`
//! 顶部映射表 66-128 行)。
//!
//! 码值常量带线值引用(`api/ctp_constant.py` 行号);错配翻译策略:能 `Option`
//! 的全 `Option`,由调用方按原稿行为处置(合约行静默丢/委托行 info 日志丢/
//! 撤单 parse 失败 console 级特价)。

use crate::wire::{
    DepthMarketData, ErrorField, InputOrderAction, InstrumentField, InvestorPositionField,
    OrderField, TradeField, TradingAccountField,
};
use ek_data::account::AccountData;
use ek_data::constant::{Asset, Direction, Exchange, InstrumentType, Offset, OrderType, Status};
use ek_data::contract::ContractData;
use ek_data::order::OrderData;
use ek_data::tick::TickData;
use ek_data::time::DtNs;
use ek_data::trade::TradeData;
use std::time::{SystemTime, UNIX_EPOCH};

// ================ CTP 码值(原稿 `constants` 表;线值取 api/ctp_constant.py) ================

/// 浮点极值标识(原稿 127 行 `MAX_FLOAT = sys.float_info.max`;
/// IEEE-754 与 Rust `f64::MAX` 同值)。
pub const MAX_FLOAT: f64 = f64::MAX;

/// 委托状态码(常量 120-128):`'0'`全成交/`'1'`部分成交尚在队列/`'3'`未成交尚在队列/
/// `'5'`已撤销/`'a'`未知;原稿 STATUS_CTP2VT 只登记这五键(67-73)。
const OST_ALL_TRADED: &str = "0";
const OST_PART_TRADED_Q: &str = "1";
const OST_NO_TRADE_Q: &str = "3";
const OST_PART_TRADED_NQ: &str = "2";
const OST_NO_TRADE_NQ: &str = "4";
const OST_CANCELED: &str = "5";
const OST_UNKNOWN: &str = "a";

/// 报单方向/持仓方向码(常量 163-169):买 `'0'`/卖 `'1'`/净 `'1'`/多 `'2'`/空 `'3'`;
/// 原稿 DIRECTION_CTP2VT 把 D_Buy/D_Sell 与 PD_Long/PD_Short 合并一表(80-82)。
const D_BUY: &str = "0";
const D_SELL: &str = "1";
/// 持仓方向码:净 `'1'`(槽位带说明,不参表——注意 CTP 码值冲突:PD_Net 与
/// D_Sell 都是 `'1'`,原稿 dict 同冲突,`'1'` 一律解析为 SHORT,行为逐字保留)。
#[allow(dead_code)]
const PD_NET: &str = "1";
const PD_LONG: &str = "2";
const PD_SHORT: &str = "3";

/// 开平标志码(常量 206-212 / OFEN 变体 1118-1124):开 `'0'`/平 `'1'`/平今 `'3'`/
/// 平昨 `'4'`;原稿用 OFEN_* 线值(94-100)。
const OFEN_OPEN: &str = "0";
const OFEN_CLOSE: &str = "1";
const OFEN_CLOSE_TODAY: &str = "3";
const OFEN_CLOSE_YESTERDAY: &str = "4";

/// 报单价格类型码(190-192):市价 `'1'`/限价 `'2'`。
const OPT_ANY_PRICE: &str = "1";
const OPT_LIMIT_PRICE: &str = "2";

/// 有效期类型码(233/235):IOC `'1'`/GFD `'3'`。
const TC_IOC: &str = "1";
const TC_GFD: &str = "3";

/// 成交量类型码(239/241):任意量 `'1'`/全部量 `'3'`。
const VC_AV: &str = "1";
const VC_CV: &str = "3";

/// 产品类码(143-149):期货 `'1'`/期权 `'2'`/组合 `'3'`/现货期权 `'6'`;
/// 原稿 PRODUCT_CTP2VT 这四键(113-118)。
const PC_FUTURES: &str = "1";
const PC_OPTIONS: &str = "2";
/// 产品类码(143-149):期货 `'1'`/期权 `'2'`/组合 `'3'`/现货期权 `'6'`;
/// 原稿 PRODUCT_CTP2VT 这四键(113-118)。
///
/// **0.12.0 改**:组合 `'3'` 与税式期货 `'7'` 不再丢弃 —— `ek-data` 的
/// [`InstrumentType`] 早有 `SPREAD` 变体,用"资产大类 + 形态"正交表达即可
/// (`asset = FUTURES` + `instrument_type = SPREAD`),不必等 `Asset` 有 SPREAD。
/// 这修正了 `D-PC` 记档的"等 ek-data 生态有 SPREAD 后再统一"——条件已具备。
const PC_COMBINATION: &str = "3";
const PC_SPOT_OPTION: &str = "6";
/// 税式期货(CTP 6.7.7 新增,`THOST_FTDC_PC_TAS = '7'`;SimNow 合约表实测含此类)。
const PC_TAS: &str = "7";

// ================ 产品类白名单(网关勾选) ================

/// 网关收录的产品类白名单(CTP 单字符码 `THOST_FTDC_PC_*`)。
///
/// 语义(D-PC-FILTER,DESIGN.md):**查询侧不过滤**(原稿 `reqQryInstrument({})` 全量,
/// 且实测三个查询口都无法按类型过滤),**收录侧严格丢弃** —— 不在名单内的合约行
/// 既不进共享合约表,也不上抛 `eContract`。
///
/// 空名单**绝不等于「全丢」**:一律回落默认(期货)。理由不是便利,是守卫 ——
/// `contracts` 为空会让持仓查询整条被跳过(driver.rs 的 `contracts.is_empty()` 守卫),
/// 一次误配置就把持仓数据关掉。
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProductClasses(pub Vec<String>);

impl ProductClasses {
    /// 默认勾选:只有期货。
    pub fn default_classes() -> Vec<String> {
        vec![PC_FUTURES.to_string()]
    }

    /// 归一化:去首尾空白、去重、丢弃非法码(CTP 产品类码是单字符),
    /// 结果为空则回落 [`ProductClasses::default_classes`]。返回有序去重表。
    pub fn normalize(&self) -> Vec<String> {
        let mut out: Vec<String> = self
            .0
            .iter()
            .map(|c| c.trim().to_string())
            .filter(|c| c.chars().count() == 1 && !c.is_empty())
            .collect();
        out.sort();
        out.dedup();
        if out.is_empty() {
            return Self::default_classes();
        }
        out
    }

    /// 该产品类码是否收录。
    pub fn accepts(&self, product_class: &str) -> bool {
        self.normalize().iter().any(|c| c == product_class)
    }
}

// ================ 枚举翻译 ================

/// 交易所代码 → [`Exchange`](原稿 EXCHANGE_CTP2VT 103-110 的**内联 match**
/// 六键,不依赖 ek-data `Exchange::ALL` 变体顺序,避免跨 crate 耦合;miss → `None`)。
pub fn exchange_of(exchange_id: &str) -> Option<Exchange> {
    match exchange_id {
        "CFFEX" => Some(Exchange::CFFEX),
        "SHFE" => Some(Exchange::SHFE),
        "CZCE" => Some(Exchange::CZCE),
        "DCE" => Some(Exchange::DCE),
        "INE" => Some(Exchange::INE),
        "GFEX" => Some(Exchange::GFEX),
        _ => None,
    }
}

/// 产品类码 → [`Asset`](原稿 PRODUCT_CTP2VT;miss → `None`,调用方填
/// [`Asset::UNKNOWN`](0.12.0 起不再丢行))。
///
/// 偏差记录(D-PC,DESIGN.md):原稿把 `PC_Combination('3')` 映到 `Asset.SPREAD`
/// —— `Asset` 无 SPREAD 变体。**0.12.0 订正**:组合类映到 `FUTURES`,由
/// [`instrument_type_from`] 给出 `InstrumentType::SPREAD` 作细分形态(正交表达,
/// 与原稿"组合属于期货大类"的语义等价);`'7'` 税式期货同法映 `FUTURES` +
/// `FUTURES_CONTRACT`。真正判不出资产的码(`'4'` 现货 / `'5'` EFP / `'I'` MI)
/// 由调用方填 `Asset::UNKNOWN` —— **仍然不丢行**,只计数显形。
pub fn asset_from(product_class: &str) -> Option<Asset> {
    match product_class {
        PC_FUTURES | PC_COMBINATION | PC_TAS => Some(Asset::FUTURES),
        PC_OPTIONS | PC_SPOT_OPTION => Some(Asset::OPTION),
        _ => None,
    }
}

/// 产品类码 → [`InstrumentType`](组合/税式期货的细分形态;0.12.0 新增)。
///
/// `None` = 本码没有额外形态信息(期货/期权就是它们自己),不是"失败"。
pub fn instrument_type_from(product_class: &str) -> Option<InstrumentType> {
    match product_class {
        PC_COMBINATION => Some(InstrumentType::SPREAD),
        // TAS = 结算价交易,标的仍是期货合约本体。
        PC_TAS => Some(InstrumentType::FUTURES_CONTRACT),
        _ => None,
    }
}

/// 委托状态码 → [`Status`](原稿 STATUS_CTP2VT 五键;miss → `None`,
/// 原稿行为 = `write_log` 后丢弃该行)。
pub fn status_of(code: &str) -> Option<Status> {
    match code {
        OST_NO_TRADE_Q => Some(Status::NOTTRADED),
        OST_PART_TRADED_Q => Some(Status::PARTTRADED),
        OST_ALL_TRADED => Some(Status::ALLTRADED),
        OST_PART_TRADED_NQ => Some(Status::PARTTRADED),
        OST_NO_TRADE_NQ => Some(Status::NOTTRADED),
        OST_CANCELED => Some(Status::CANCELLED),
        OST_UNKNOWN => Some(Status::SUBMITTING),
        _ => None,
    }
}

/// 方向码 → [`Direction`](D_* 与 PD_* 合并表,原稿 80-82)。
pub fn direction_from(code: &str) -> Option<Direction> {
    match code {
        D_BUY | PD_LONG => Some(Direction::LONG),
        D_SELL | PD_SHORT => Some(Direction::SHORT),
        _ => None,
    }
}

/// 开平码(OFEN_*)→ [`Offset`]。
pub fn offset_from(code: &str) -> Option<Offset> {
    match code {
        OFEN_OPEN => Some(Offset::OPEN),
        OFEN_CLOSE => Some(Offset::CLOSE),
        OFEN_CLOSE_TODAY => Some(Offset::CLOSETODAY),
        OFEN_CLOSE_YESTERDAY => Some(Offset::CLOSEYESTERDAY),
        _ => None,
    }
}

/// (价格类型, 有效期, 成交量类型)三元组 → [`OrderType`](原稿 ORDERTYPE_VT2CTP
/// 85-90 反演;misse → `None`,原稿 write_log 后丢行)。
pub fn order_type_from(price_type: &str, time_cond: &str, volume_cond: &str) -> Option<OrderType> {
    match (price_type, time_cond, volume_cond) {
        (OPT_LIMIT_PRICE, TC_GFD, VC_AV) => Some(OrderType::LIMIT),
        (OPT_ANY_PRICE, TC_GFD, VC_AV) => Some(OrderType::MARKET),
        (OPT_LIMIT_PRICE, TC_IOC, VC_AV) => Some(OrderType::FAK),
        (OPT_LIMIT_PRICE, TC_IOC, VC_CV) => Some(OrderType::FOK),
        _ => None,
    }
}

/// 发单用的方向/开平/类型三元组回探(原稿 DIRECTION_VT2CTP / OFFSET_VT2CTP /
/// ORDERTYPE_VT2CTP 76-90;`OrderType` 回撤三元组是正演)。
pub fn direction_to(d: Direction) -> Option<&'static str> {
    match d {
        Direction::LONG => Some(D_BUY),
        Direction::SHORT => Some(D_SELL),
        _ => None,
    }
}

/// [`Offset`] → 开平码(OFEN_*);`Offset::NONE` 不在原稿表内(misse → `None`)。
pub fn offset_to(exchange: Exchange, o: Offset) -> Option<&'static str> {
    // 开平语义按交易所折叠:CloseToday/CloseYesterday 只有上期所(SHFE)与能源中心(INE)
    // 认;其余交易所只认 Close,直接发 '3'/'4' 会被 CTP 拒("开平标志错误")。
    let o = match o {
        Offset::CLOSETODAY | Offset::CLOSEYESTERDAY
            if exchange != Exchange::SHFE && exchange != Exchange::INE =>
        {
            Offset::CLOSE
        }
        other => other,
    };
    match o {
        Offset::OPEN => Some(OFEN_OPEN),
        Offset::CLOSE => Some(OFEN_CLOSE),
        Offset::CLOSETODAY => Some(OFEN_CLOSE_TODAY),
        Offset::CLOSEYESTERDAY => Some(OFEN_CLOSE_YESTERDAY),
        _ => None,
    }
}

/// [`OrderType`] → (价格类型码, 有效期码, 量码) 发单三元组。
pub fn order_type_to(t: OrderType) -> Option<(&'static str, &'static str, &'static str)> {
    match t {
        OrderType::LIMIT => Some((OPT_LIMIT_PRICE, TC_GFD, VC_AV)),
        OrderType::MARKET => Some((OPT_ANY_PRICE, TC_GFD, VC_AV)),
        OrderType::FAK => Some((OPT_LIMIT_PRICE, TC_IOC, VC_AV)),
        OrderType::FOK => Some((OPT_LIMIT_PRICE, TC_IOC, VC_CV)),
        _ => None,
    }
}

// ================ 精度与时间 ================

/// 异常浮点值修正(原稿 895-899 行):MAX_FLOAT → 0。
pub fn adjust_price(price: f64) -> f64 {
    if price == MAX_FLOAT { 0.0 } else { price }
}

/// Howard Hinnant civil→days 算法(自 1970-01-01 的天数;零依赖)。
///
/// 注:`doy` 里的 `(153*mx + 2)/5` 那个 **`+2` 不能写成 `-2`** —— 写成 `-2` 会让
/// **部分日期整体差一天**(实测 2026-01-01、2026-04-15/16 差一天,而 2026-03-01、
/// 2026-12-30 恰好正确,所以自比型单测照不出来)。2026-10-15 实盘联调靠"行情新鲜度"
/// 与 ek-data `civil_to_nanos` 独立真值比对才抓到。
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146097 + doe - 719468
}

/// CTP 时间戳 → [`DtNs`](UTC 纪元纳秒)。
///
/// date = "YYYYMMDD"、time = "HH:MM:SS";约定(D-TZ):CTP 原稿把该组合按
/// `CHINA_TZ = Asia/Shanghai` 处理,本实现按【固定 +08:00】换算为 UTC 纪元纳秒。
/// 畸形输入(长度/数字缺失)→ `None`,调用方全量丢行(原稿会 strptime 异常)。
pub fn ctp_datetime(date: &str, time: &str, millis: i64) -> Option<DtNs> {
    // 长度按**字节**判,所以必须先证明两边都是 ASCII:非 ASCII 输入(GBK 报文经 shim
    // 转成 UTF-8 后的汉字)会让下面的 `&time[..2]` 落在多字节字符中间 —— 那是 str 切片
    // panic,而本函数跑在 CTP 回调帧里(edition 2024 的 `extern "C"` 遇 panic 直接
    // abort,全仓无 catch_unwind)。8 字节且全 ASCII 之后,下面每个下标都是字符边界。
    if date.len() != 8 || time.len() != 8 || !date.is_ascii() || !time.is_ascii() {
        return None;
    }
    let digits_ok = |s: &str| s.bytes().all(|b: u8| b.is_ascii_digit());
    if !(digits_ok(date)
        && digits_ok(&time[..2])
        && digits_ok(&time[3..5])
        && digits_ok(&time[6..8]))
    {
        return None;
    }
    let (y, m, d) = (
        date[0..4].parse::<i64>().ok()?,
        date[4..6].parse::<i64>().ok()?,
        date[6..8].parse::<i64>().ok()?,
    );
    let (h, mi, s) = (
        time[0..2].parse::<i64>().ok()?,
        time[3..5].parse::<i64>().ok()?,
        time[6..8].parse::<i64>().ok()?,
    );
    if !((1..=12).contains(&m) && h < 24 && mi < 60 && s < 60) {
        return None;
    }
    // 溢出保护:年月日与毫秒都是经纪人可控字段;公元 2262 之后纳秒不再装得进 i64。
    // 溢出 → `None` 丢行(D-STRUCT-SKIP),而不是 dbg 里 panic(回调帧里 = abort)、
    // release 里静默回绕成错值。
    // CTP 报文的日期/时间是【北京本地墙钟】(原稿按 CHINA_TZ 建 tz-aware datetime),
    // 而 DtNs 是 **UTC 纪元纳秒**(ek-data `time.rs:3-6/29-30`)⇒ 换 UTC 必须**减** 8 小时。
    // 2026-10-15 实盘联调暴露:此前写成 `+ 8*3_600`,所有 tick/委托/成交时间戳整体偏
    // +16 小时(拿"行情新鲜度"跟 `now_nanos()` 一比立刻显形)。
    let secs = days_from_civil(y, m, d)
        .checked_mul(86_400)?
        .checked_add(h * 3_600 + mi * 60 + s - 8 * 3_600)?;
    secs.checked_mul(1_000_000_000)?
        .checked_add(millis.checked_mul(1_000_000)?)
}

/// 纪元毫秒(0.9.0 状态口用:登录/回报/断开的「最近时刻」都以此为准)。
///
/// 口径:ek-data `time::now_nanos()`(墙上时钟,纪元纳秒)**除以 1e6** —— 不另起
/// 一个时钟源,状态口的时刻与 tick/委托/成交的时间戳同源于同一把钟,消费侧
/// (ek-ui)拿 `sampled_ms` 减别的 crate 的 `now_nanos()/1e6` 才是同一把尺。
/// 不用单调钟:`ctp.status` 的回带值要被**跨插件、跨进程重启**的界面读,
/// 单调钟的零点在别处没有意义;差值由消费侧做减法,不受时区影响。
#[must_use]
pub fn now_epoch_ms() -> i64 {
    ek_data::time::now_nanos() / 1_000_000
}

/// 上海本地当日("YYYYMMDD";eTimer 秒级刷新口径,对齐原稿 md 的 update_date 406-408)。
pub fn shanghai_now_date() -> String {
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
        + 8 * 3_600;
    let days = secs.div_euclid(86_400);
    // 反算 civil(经 Hinnant days_from_civil 的逆,长年等价于儒略法;40 年内无损)
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!("{y:04}{m:02}{d:02}")
}

// ================ 对象映射(wire → ek-data) ================

/// CTP 错误行 → 日志正文(原稿 `write_error` 216-222:`"{msg},代码:{id},信息:{m}"`)。
pub fn error_text(msg: &str, e: &ErrorField) -> String {
    format!("{},代码:{},信息:{}", msg, e.error_id, e.error_msg)
}

// ================ 映射 ================
//
// 0.12.0 删除了原先的 `Mapped<T>` 枚举(它曾是映射层的"可以丢"出口:
// `Ok(T)` / `Skip(原因)`)。零丢弃改造后,五个 `*_from` 全部改成直接返回对象
// 类型:**编译器不再允许**这个模块产出"整行消失"的结果。
//
// 删掉那个枚举不是清理,而是把纪律从"注释里的约定"升级成"类型系统的约束"
// —— 想再丢一行,得先把返回类型加回来,那一步一定会被 review 看到。
//
// 历史:`Mapped::Skip` 曾在 21 处吞掉入向行(清单见
// `docs/ek-ctp-no-drop-refactor-plan-2026-10-31.md`)。

/// "YYYYMMDD" → `Option<i32>`(8 位 ASCII 数字严格验;缺省/畸形 ⇒ `None`)。
///
/// 附加轴专用:CTP 日期字符串恒为 ASCII(GBK↔UTF-8 转换不改变它)。
/// 全零串 `"00000000"` 视为缺省(校历无效的整零值不该作为日历标签上岸)。
fn yyyymmdd_i32(s: &str) -> Option<i32> {
    if s.len() != 8 || !s.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    match s.parse::<i32>() {
        Ok(0) => None,
        Ok(v) => Some(v),
        Err(_) => None,
    }
}

/// 行情行 → [`TickData`](原稿 301-366。
///
/// **0.12.0(边界零丢弃)本函数不再返回 `Mapped`** —— 行情行没有"丢"这条出口。
/// - 时间戳不可得(空 / 畸形)→ `datetime_invalid = true`,`datetime` 留 `DtNs` 缺省;
///   量价盘口照上账。原稿在 303-305 / 319-322 两处**整条丢**,而丢掉的其实是
///   "一条真实成交的量价" —— 只是时间轴不可用。
/// - 合约不在册(`D-XFALLBACK`)→ 交易所取报文 `ExchangeID`(再兜底 `UNKNOWN`),
///   `name` 留空。旧实现整条丢 —— 而"合约查询还没跑完"与"这个合约真的没行情"
///   在界面上长得一模一样,用户无从分辨。
/// - 交易日口径:ActionDay 空或大商所 → 用上层传入的 current_date(313-317)。
/// - 大商所特判原样:DCE 的 ActionDay 不能当自然日用 ⇒ 全部 current_date
///   (`contract.exchange == Exchange::DCE` 或空 action_day)。
/// - 时间戳带毫秒:`.{UpdateMillisec}`(319-320)。
/// - `datetime` 之外的两条日期轴(记档偏差,原稿网关不产出;下游 2514-2521 才用启发式
///   推交易日):`trading_day` = 报文 `TradingDay` 原值(业务日权威);`action_day` =
///   参与拼 `datetime` 的那个日期串(规则化自然日)。两轴都保留报文缺省 → `None`。
/// - 二至五档骨架:`BidVolume2 或 AskVolume2 非零`才添盘口(345-364)。
/// - `last_volume` 原稿网关**不复算**(TickData 缺省 0),此处也照留。
pub fn tick_from(
    dm: &DepthMarketData,
    contract: Option<&ContractData>,
    gw: &str,
    current_date: &str,
) -> TickData {
    let exchange = match contract {
        Some(c) => c.exchange,
        // 合约不在册:交易所取报文镜像(取不到才 `UNKNOWN`,不猜)
        None => exchange_of(&dm.exchange_id).unwrap_or(Exchange::UNKNOWN),
    };
    let date_str = if dm.action_day.is_empty() || exchange == Exchange::DCE {
        current_date.to_string()
    } else {
        dm.action_day.clone()
    };
    // 时间戳不可得 ≠ 这条行情不存在:留 `datetime_invalid = true` 显式标注。
    let dt = ctp_datetime(&date_str, &dm.update_time, dm.update_millisec);
    let trading_day = yyyymmdd_i32(&dm.trading_day);
    let action_day = yyyymmdd_i32(&date_str);
    let mut tick = TickData {
        gateway_name: gw.to_string(),
        symbol: dm.instrument_id.clone(),
        exchange,
        datetime: dt.unwrap_or_default(),
        // 已知不可用才标 true;默认 false = 沿今天的行为(时间有效)。
        datetime_invalid: dt.is_none(),
        trading_day,
        action_day,
        update_time: dm.update_time.clone(),
        update_millisec: dm.update_millisec,
        // 合约不在册 ⇒ 名字与乘数富化不了,留空/零;量价字段照上账(红线①)
        name: contract.map(|c| c.name.clone()).unwrap_or_default(),
        volume: dm.volume,
        turnover: dm.turnover,
        open_interest: dm.open_interest,
        last_price: adjust_price(dm.last_price),
        limit_up: adjust_price(dm.upper_limit_price),
        limit_down: adjust_price(dm.lower_limit_price),
        open_price: adjust_price(dm.open_price),
        high_price: adjust_price(dm.highest_price),
        low_price: adjust_price(dm.lowest_price),
        pre_close: adjust_price(dm.pre_close_price),
        bid_price_1: adjust_price(dm.bid_price1),
        ask_price_1: adjust_price(dm.ask_price1),
        bid_volume_1: dm.bid_volume1,
        ask_volume_1: dm.ask_volume1,
        // ── 以下二十个字段快照不直接给,显式写默认值,不靠 `..Default` ─────
        // 二到五档:浅档行情只有一档,默认 0;**有值时下面按包覆盖**。
        bid_price_2: 0.0,
        bid_price_3: 0.0,
        bid_price_4: 0.0,
        bid_price_5: 0.0,
        ask_price_2: 0.0,
        ask_price_3: 0.0,
        ask_price_4: 0.0,
        ask_price_5: 0.0,
        bid_volume_2: 0.0,
        bid_volume_3: 0.0,
        bid_volume_4: 0.0,
        bid_volume_5: 0.0,
        ask_volume_2: 0.0,
        ask_volume_3: 0.0,
        ask_volume_4: 0.0,
        ask_volume_5: 0.0,
        // 现手:CTP 快照**没有**"本次增量"字段,只能靠前后帧成交量差分;
        // 映射层无状态、算不了,留 0 交给上层。
        last_volume: 0.0,
        // 本地接收时刻:要本地钟,映射层不持有时钟。
        localtime: None,
        // 涨跌幅:需要昨结算价,快照与合约表都不直接给,留 0。
        pct_change: 0.0,
    };
    if dm.bid_volume2 != 0.0 || dm.ask_volume2 != 0.0 {
        tick.bid_price_2 = adjust_price(dm.bid_price2);
        tick.bid_price_3 = adjust_price(dm.bid_price3);
        tick.bid_price_4 = adjust_price(dm.bid_price4);
        tick.bid_price_5 = adjust_price(dm.bid_price5);
        tick.ask_price_2 = adjust_price(dm.ask_price2);
        tick.ask_price_3 = adjust_price(dm.ask_price3);
        tick.ask_price_4 = adjust_price(dm.ask_price4);
        tick.ask_price_5 = adjust_price(dm.ask_price5);
        tick.bid_volume_2 = dm.bid_volume2;
        tick.bid_volume_3 = dm.bid_volume3;
        tick.bid_volume_4 = dm.bid_volume4;
        tick.bid_volume_5 = dm.bid_volume5;
        tick.ask_volume_2 = dm.ask_volume2;
        tick.ask_volume_3 = dm.ask_volume3;
        tick.ask_volume_4 = dm.ask_volume4;
        tick.ask_volume_5 = dm.ask_volume5;
    }
    tick
}

/// 合约行 → [`ContractData`](原稿 632-654)。
///
/// **0.12.0(边界零丢弃)**:不返回 `Mapped` —— 勾选已在调用方判过(唯一过滤器),
/// 到了这里就必须上岸。两个"翻译不了"填表达:
/// - 交易所码未映射 → [`Exchange::UNKNOWN`](原稿此处 `KeyError` 崩回调)
/// - 产品类码未映射 → [`Asset::UNKNOWN`](原稿此处 `if product:` 静默丢行)
pub fn contract_from(inf: &InstrumentField, gw: &str) -> ContractData {
    ContractData {
        gateway_name: gw.to_string(),
        symbol: inf.instrument_id.clone(),
        name: inf.instrument_name.clone(),
        exchange: exchange_of(&inf.exchange_id).unwrap_or(Exchange::UNKNOWN),
        asset: asset_from(&inf.product_class).unwrap_or(Asset::UNKNOWN),
        // 0.12.0:组合 → SPREAD、TAS → FUTURES_CONTRACT(正交形态,不占 Asset 变体)。
        instrument_type: instrument_type_from(&inf.product_class),
        size: inf.volume_multiple,
        price_tick: inf.price_tick,
        max_limit_order_volume: Some(inf.max_limit_order_volume),
        min_limit_order_volume: Some(inf.min_limit_order_volume),
        max_market_order_volume: Some(inf.max_market_order_volume),
        min_market_order_volume: Some(inf.min_market_order_volume),
        delivery_year: Some(inf.delivery_year as i32),
        delivery_month: Some(inf.delivery_month as i32),
        product_id: Some(inf.product_id.clone()),
        // D-CTR-FILL:原稿不填(缺省 None),这里显式填。
        is_trading: Some(inf.is_trading == 1),
        // 上市日(空 = 柜台未给 → None)。合约表没有涨跌停价,那两个字段
        // 保持 None 是对的:真值只在行情 tick 的 limit_up/limit_down 里。
        open_date: (!inf.open_date.is_empty()).then(|| inf.open_date.clone()),
        // ── 以下四个字段 CTP 合约表**不提供**,显式写 None,不靠 `..Default` ──
        // 涨跌停价:合约表**没有** UpperLimitPrice/LowerLimitPrice(已对 SDK 核实),
        // 真值只在 DepthMarketData,由 `TickData.limit_up/limit_down` 承担。
        // 这两个字段保持 None 是**正确的**,不是漏填。
        up_stop_price: None,
        down_stop_price: None,
        // `pre_close`(昨收)只在 `CThostFtdcDepthMarketDataField` 里,
        // 合约查询回报没有;要拿只能从行情 tick 或另查。
        pre_close: None,
        // 流通股本 / 总股本:这两个是 **A 股概念**,期货没有。
        // 它们是从股票框架搬过来的字段,CTP 任何结构都不给,永远 None。
        float_volume: None,
        total_volume: None,
        // 合约交易状态来自**另一个查询**(`CThostFtdcInstrumentStatusField`),
        // 不在合约表字段里。合约表只有 `InstLifePhase`(生命周期),语义不同。
        instrument_status: None,
    }
}

/// 单委托行 → [`OrderData`](原稿 onRtnOrder 669-716;订单号三段下划线)。
///
/// 0.7.0(甲):`contract` 参数退役 —— `symbol` 取报文 InstrumentID,
/// `exchange` 由调用方用报文 ExchangeID 经 [`exchange_of`] 预映射后传入。
///
/// **0.12.0(边界零丢弃,D-NO-DROP)**:本函数**不再返回 `Mapped`** —— 委托行
/// 没有"丢"这条出口。翻译不了的值一律填表达,由调用方计数显形:
/// - 状态码未映射 → [`Status::UNKNOWN`],不替柜台猜在途
/// - 类型三元组未映射 → [`OrderType::UNKNOWN`],不借 `LIMIT` 顶替
/// - 时间戳畸形 → `datetime: None`(原稿此处 `strptime` 抛异常,整条丢)
/// - 方向码未映射 → `direction: None`(Python 模型本身允许 `None`,object.py:163)
/// - 开平码未映射 → [`Offset::NONE`],原稿拒单面就这么填(`ctp_gateway.py:505`)
pub fn order_from(of: &OrderField, exchange: Exchange, gw: &str) -> OrderData {
    // 原稿 681:委托号先算(日志/载荷都带完整订单号)。
    let orderid = format!("{}_{}_{}", of.front_id, of.session_id, of.order_ref);
    OrderData {
        gateway_name: gw.to_string(),
        symbol: of.instrument_id.clone(),
        exchange,
        orderid,
        order_type: order_type_from(
            &of.order_price_type,
            &of.time_condition,
            &of.volume_condition,
        )
        .unwrap_or(OrderType::UNKNOWN),
        direction: direction_from(&of.direction),
        offset: offset_from(&of.comb_offset_flag).unwrap_or(Offset::NONE),
        price: adjust_price(of.limit_price),
        volume: of.volume_total_original,
        traded: of.volume_traded,
        status: status_of(&of.order_status).unwrap_or(Status::UNKNOWN),
        // 原稿把 InsertDate+InsertTime 直接 strptime,畸形即抛;这里给 None,
        // 行照上账(时间不可得 ≠ 委托不存在)。
        datetime: ctp_datetime(&of.insert_date, &of.insert_time, 0),
        // ── 以下四个字段柜台**不提供**,显式写出来,不留 `..Default` ────────
        // 老写法用 `..OrderData::default()` 兜底,后果是 `ek-data` 以后新增
        // 任何字段都静默变默认值、编译器一声不响(`traded_price` 就这么躺了
        // 好几轮)。写全了以后,加字段会直接编译失败,逼人面对。
        //
        // `reference` 是下单时本地附言,柜台回报不带。
        reference: String::new(),
        // `name` 由 name_enrich 段按合约表补,映射层不知道合约中文名。
        name: String::new(),
        // CThostFtdcOrderField **没有** StatusMsg 列(与 InputOrder 不同),
        // 所以废单原因拿不到 —— 柜台限制,不是漏映射。
        status_msg: String::new(),
        // 委托单没有成交价:价在 `TradeData.price` 里,一笔委托可能多笔成交、
        // 多个价,"委托的成交均价"这个概念本身不成立。
        traded_price: 0.0,
    }
}

/// 单成交行 → [`TradeData`](原稿 onRtnTrade 720-747;仓位报单号由 sysid 表换算)。
///
/// 0.7.0(甲):`contract` 参数退役 —— 语义同 [`order_from`];原稿的成交
/// 更新本来就取 `trade.exchange`(converter 语义),这里只是把同一条纪律
/// 落到映射层。
///
/// **0.12.0**:同 [`order_from`],不返回 `Mapped` —— 成交更没有"丢"的出口
/// (丢一条成交 = 均价/盈亏永久错)。时间戳畸形 → `None`,方向/开平未映射 →
/// `None`/`NONE`。
pub fn trade_from(tf: &TradeField, orderid: &str, exchange: Exchange, gw: &str) -> TradeData {
    TradeData {
        gateway_name: gw.to_string(),
        symbol: tf.instrument_id.clone(),
        exchange,
        orderid: orderid.to_string(),
        tradeid: tf.trade_id.clone(),
        direction: direction_from(&tf.direction),
        offset: offset_from(&tf.offset_flag).unwrap_or(Offset::NONE),
        price: tf.price,
        volume: tf.volume,
        datetime: ctp_datetime(&tf.trade_date, &tf.trade_time, 0),
        // ── 以下四个字段柜台不提供,显式留白,不靠 `..Default` ──────────────
        // 手续费/滑点/平仓盈亏要额外查费率或本地算;成交额 = 价 × 量 × 合约乘数,
        // 乘数在合约表、映射层拿不到。**一律写 0 而不是编造** —— 拿 0 出来
        // 比拿一个假数安全,下游能看出"这项没有"。
        commission: 0.0,
        slippage: 0.0,
        trade_pnl: 0.0,
        // 合约中文名同样由 name_enrich 补,成交回报只带代码。
        name: String::new(),
        traded_amount: 0.0,
    }
}

/// 资金行 → [`AccountData`](原稿 604-610)。
///
/// frozen = FrozenMargin + FrozenCash + FrozenCommission 三项求和;
/// CTP `Available` 字段**按原稿语义属派生面**(balance − frozen 的差 =
/// 占用保证金),ek-data 的 available() 为派生 —— 差额详见 DESIGN.md D-AVAIL。
pub fn account_from(ta: &TradingAccountField, gw: &str) -> AccountData {
    AccountData {
        gateway_name: gw.to_string(),
        accountid: ta.account_id.clone(),
        balance: ta.balance,
        frozen: ta.frozen_margin + ta.frozen_cash + ta.frozen_commission,
    }
}

/// 累积一次仓位行(原稿 546-586;合并语义:键 = (InstrumentID, PosiDirection),
/// SHFE/INE 昨仓特判,对向仓量记冻结)。
pub fn accumulate_position(
    row: &InvestorPositionField,
    pos: &mut ek_data::PositionData,
    exchange: Exchange,
    contract_size: f64,
) {
    // 上期系昨仓特判(原稿 559-565 逐字,**零补全**):
    //   if exchange in {SHFE, INE}:
    //       if YdPosition and not TodayPosition: yd_volume = Position
    //   else:                                # 连回上 if(非上期系)
    //       yd_volume = Position - TodayPosition
    // 注意两处均为**赋值**(562/565),非累加——SHFE 今/昨两行同键时,昨行
    // 命中特判最后一次赋值,结果与原稿一致;不满足特判则**什么都不写**。
    if exchange == Exchange::SHFE || exchange == Exchange::INE {
        if row.yd_position != 0.0 && row.today_position == 0.0 {
            pos.yd_volume = row.position;
        }
    } else {
        pos.yd_volume = row.position - row.today_position;
    }
    // 累积量与盈亏(571-580):volume += Position;pnl += PositionProfit;
    // 均价 = (上成本 + 本行 PositionCost) / (量×乘数),量与乘数皆非零才写。
    let cost = pos.price * pos.volume * contract_size;
    pos.volume += row.position;
    pos.pnl += row.position_profit;
    if pos.volume != 0.0 && contract_size != 0.0 {
        pos.price = (cost + row.position_cost) / (pos.volume * contract_size);
    }
    // 冻结量:多头仓累计空头冻结,空头仓累计多头冻结(583-586)。
    if pos.direction == Direction::LONG {
        pos.frozen += row.short_frozen;
    } else {
        pos.frozen += row.long_frozen;
    }
}

/// 单仓位行建仓初值(原稿 551-556;零值骨架由驱动层累加)。
pub fn new_position_data(
    symbol: &str,
    exchange: Exchange,
    direction: Option<Direction>,
    gw: &str,
) -> Option<ek_data::PositionData> {
    Some(ek_data::PositionData {
        gateway_name: gw.to_string(),
        symbol: symbol.to_string(),
        exchange,
        direction: direction?,
        ..ek_data::PositionData::default()
    })
}

// ================ 下单/撤单请求构建(P1 面) ================

/// 撤单请求的委托号解析(原稿 `cancel_order` 858 行 `req.orderid.split("_")`)。
///
/// 三段 `front_session_ref`(原稿 `f"{frontid}_{sessionid}_{order_ref}"`);
/// 非三段或 front/session 非整数 → `None`(原稿 int() 会抛 ValueError,
/// 本实现转结构化丢弃并记日志,DESIGN.md D6)。
pub fn cancel_action_from(
    orderid: &str,
    symbol: &str,
    exchange: Exchange,
    broker: &str,
    user: &str,
) -> Option<InputOrderAction> {
    let mut parts = orderid.split('_');
    let (front, session, ore) = (parts.next()?, parts.next()?, parts.next()?);
    if parts.next().is_some() {
        return None;
    }
    let (front_id, session_id): (i64, i64) = (front.parse().ok()?, session.parse().ok()?);
    Some(InputOrderAction {
        instrument_id: symbol.to_string(),
        exchange_id: exchange.as_str().to_string(),
        order_ref: ore.to_string(),
        front_id,
        session_id,
        // AF_Delete = '0'(常量 258;原稿 THOST_FTDC_AF_Delete)
        action_flag: "0".to_string(),
        broker_id: broker.to_string(),
        investor_id: user.to_string(),
    })
}

// ================ 边界契约:内部格式 → CTP 格式(2026-10-30 收口) ================

/// 内部符号 → CTP 裸合约代码。**出向一切字符串形参的唯一归一化点**。
///
/// 内部有两种写法:裸代码(`ag2612`)与显示全名(`SHFE.ag2612`,`ContractData::en_symbol()` 所出)。
/// 订阅 / 发单 / 撤单 / 费率查询四个入口都必须先过这里 —— CTP 只认裸代码,
/// 且交易所是**独立字段**,喂全名会拼成 `EX.EX.代码`(发单直接整体拒)。
///
/// 规则(不猜):裸代码原样;点号前是**已知交易所码**则取点号后;其余一律 `None`。
pub fn instrument_id(raw: &str) -> Option<String> {
    let s = raw.trim();
    if s.is_empty() {
        return None;
    }
    match s.split_once('.') {
        None => Some(s.to_string()),
        Some((head, rest)) => {
            let rest = rest.trim();
            if head.is_empty() || rest.is_empty() {
                return None;
            }
            // 前缀大小写不敏感:CTP 侧只认大写码,内部/用户输入常写小写(`shfe.ag2612`)。
            exchange_of(&head.trim().to_ascii_uppercase()).map(|_| rest.to_string())
        }
    }
}

/// 持仓方向码 → [`Direction`],净持仓按数量正负判。
///
/// CTP 的 `PosiDirection` 在净持仓交易所(CFFEX)报 `'1'`,与卖 `'1'` 同码;
/// 老实现一律解析成 SHORT,多头净仓会被翻成空头(方向与盈亏符号同时错)。
/// 这里:净码按 `Position` 正负还原(>0 多 / <0 空 / =0 无净仓 → `None`);
/// 多空码照旧。
pub fn position_direction(code: &str, position: f64) -> Option<Direction> {
    match code {
        PD_NET => match position.partial_cmp(&0.0)? {
            std::cmp::Ordering::Greater => Some(Direction::LONG),
            std::cmp::Ordering::Less => Some(Direction::SHORT),
            std::cmp::Ordering::Equal => None,
        },
        PD_LONG => Some(Direction::LONG),
        PD_SHORT => Some(Direction::SHORT),
        _ => None,
    }
}
#[cfg(test)]
mod tests {
    use super::*;

    /// 上市日全链:CTP `InstrumentField.OpenDate` → `wire.open_date` → `ContractData.open_date`。
    ///
    /// 这条存在的原因:2026-11-01 审计发现该字段声明了但**从来没有值**,
    /// 补上 wire 列后必须有一条测试钉住,否则下次重构又会悄悄丢掉。
    #[test]
    fn contract_carries_open_date_from_wire() {
        let inf = InstrumentField {
            instrument_id: "rb2611".into(),
            exchange_id: "SHFE".into(),
            instrument_name: "螺纹钢2611".into(),
            product_class: "1".into(),
            volume_multiple: 10.0,
            price_tick: 1.0,
            max_limit_order_volume: 500.0,
            min_limit_order_volume: 1.0,
            max_market_order_volume: 500.0,
            min_market_order_volume: 1.0,
            delivery_year: 2026,
            delivery_month: 11,
            product_id: "rb".into(),
            is_trading: 1,
            open_date: "20260115".into(),
        };
        let c = contract_from(&inf, "ctp");
        assert_eq!(c.open_date.as_deref(), Some("20260115"), "上市日必须透传");
    }

    /// 柜台没给上市日(空串)→ `None`,不是 `Some("")`。
    /// 空串当值会让下游"有没有上市日"的判断失效。
    #[test]
    fn contract_open_date_empty_maps_to_none() {
        let inf = InstrumentField {
            instrument_id: "x".into(),
            exchange_id: "SHFE".into(),
            instrument_name: "x".into(),
            product_class: "1".into(),
            volume_multiple: 10.0,
            price_tick: 1.0,
            max_limit_order_volume: 1.0,
            min_limit_order_volume: 1.0,
            max_market_order_volume: 1.0,
            min_market_order_volume: 1.0,
            delivery_year: 2026,
            delivery_month: 1,
            product_id: "x".into(),
            is_trading: 1,
            open_date: String::new(),
        };
        let c = contract_from(&inf, "ctp");
        assert_eq!(c.open_date, None);
    }

    #[test]
    fn yyyymmdd_i32_accepts_real_dates_and_rejects_garbage() {
        assert_eq!(yyyymmdd_i32("20261015"), Some(20261015));
        // 全零串=缺省(校历无效的整零值不上岸)。
        assert_eq!(yyyymmdd_i32("00000000"), None);
        // 形状畸形:长度错/非 ASCII 数字/空串。
        assert_eq!(yyyymmdd_i32("2026101"), None);
        assert_eq!(yyyymmdd_i32("202610150"), None);
        assert_eq!(yyyymmdd_i32("2026101a"), None);
        assert_eq!(yyyymmdd_i32(""), None);
    }

    // ---- 边界契约(2026-10-30):出向归一化 / 入向补全的判据 ----

    #[test]
    fn instrument_id_accepts_bare_and_en_symbol_and_rejects_garbage() {
        // 裸代码:原样
        assert_eq!(instrument_id("ag2612").as_deref(), Some("ag2612"));
        assert_eq!(instrument_id("  cu2612 ").as_deref(), Some("cu2612"));
        // 全名(en_symbol 的形态):剥交易所前缀
        assert_eq!(instrument_id("SHFE.ag2612").as_deref(), Some("ag2612"));
        assert_eq!(instrument_id("INE.sc2612").as_deref(), Some("sc2612"));
        assert_eq!(instrument_id("CFFEX.IF2412").as_deref(), Some("IF2412"));
        // 不猜:空串 / 只有前缀 / 未知交易所前缀 → None
        assert_eq!(instrument_id(""), None);
        assert_eq!(instrument_id("   "), None);
        assert_eq!(instrument_id("SHFE."), None);
        assert_eq!(instrument_id(".ag2612"), None);
        assert_eq!(instrument_id("XX.ag2612"), None);
        // 小写前缀:CTP 只认大写码,归一时抬成大写再判
        assert_eq!(instrument_id("shfe.ag2612").as_deref(), Some("ag2612"));
        assert_eq!(instrument_id("Shfe. ag2612 ").as_deref(), Some("ag2612"));
    }

    #[test]
    fn offset_to_folds_close_today_by_exchange() {
        // 上期所 / 能源中心:保留平今/平昨
        for ex in [Exchange::SHFE, Exchange::INE] {
            assert_eq!(offset_to(ex, Offset::CLOSETODAY), Some(OFEN_CLOSE_TODAY));
            assert_eq!(
                offset_to(ex, Offset::CLOSEYESTERDAY),
                Some(OFEN_CLOSE_YESTERDAY)
            );
            assert_eq!(offset_to(ex, Offset::OPEN), Some(OFEN_OPEN));
            assert_eq!(offset_to(ex, Offset::CLOSE), Some(OFEN_CLOSE));
        }
        // 其余四所:只认 Close(直接发 '3'/'4' 会被 CTP 拒)
        for ex in [
            Exchange::CFFEX,
            Exchange::CZCE,
            Exchange::DCE,
            Exchange::GFEX,
        ] {
            assert_eq!(
                offset_to(ex, Offset::CLOSETODAY),
                Some(OFEN_CLOSE),
                "{ex:?}"
            );
            assert_eq!(
                offset_to(ex, Offset::CLOSEYESTERDAY),
                Some(OFEN_CLOSE),
                "{ex:?}"
            );
            assert_eq!(offset_to(ex, Offset::OPEN), Some(OFEN_OPEN));
            assert_eq!(offset_to(ex, Offset::CLOSE), Some(OFEN_CLOSE));
        }
    }

    #[test]
    fn status_of_covers_part_and_no_trade_not_queueing() {
        assert_eq!(status_of("2"), Some(Status::PARTTRADED));
        assert_eq!(status_of("4"), Some(Status::NOTTRADED));
        // 老五码行为不变
        assert_eq!(status_of("0"), Some(Status::ALLTRADED));
        assert_eq!(status_of("1"), Some(Status::PARTTRADED));
        assert_eq!(status_of("3"), Some(Status::NOTTRADED));
        assert_eq!(status_of("5"), Some(Status::CANCELLED));
        assert_eq!(status_of("a"), Some(Status::SUBMITTING));
        assert_eq!(status_of("z"), None);
    }

    #[test]
    fn position_direction_uses_sign_for_net_positions() {
        // CFFEX 净持仓:'1' 靠数量正负还原方向
        assert_eq!(position_direction("1", 3.0), Some(Direction::LONG));
        assert_eq!(position_direction("1", -2.0), Some(Direction::SHORT));
        assert_eq!(position_direction("1", 0.0), None);
        // 多空码照旧
        assert_eq!(position_direction("2", 5.0), Some(Direction::LONG));
        assert_eq!(position_direction("3", 5.0), Some(Direction::SHORT));
        assert_eq!(position_direction("9", 1.0), None);
    }

    #[test]
    fn order_from_normalizes_market_order_sentinel_price() {
        let of = OrderField {
            instrument_id: "ag2612".into(),
            exchange_id: "SHFE".into(),
            order_ref: "1".into(),
            front_id: 1,
            session_id: 2,
            order_status: "3".into(),
            order_price_type: "1".into(),
            time_condition: "3".into(),
            volume_condition: "1".into(),
            insert_date: "20261030".into(),
            insert_time: "00:15:00".into(),
            direction: "0".into(),
            comb_offset_flag: "0".into(),
            limit_price: MAX_FLOAT,
            volume_total_original: 1.0,
            volume_traded: 0.0,
            ..OrderField::default()
        };
        // 0.12.0:`order_from` 不再返回 `Mapped` —— 委托行没有"丢"的出口。
        let order = order_from(&of, Exchange::SHFE, "ctp");
        assert_eq!(order.price, 0.0);
        assert_eq!(order.symbol, "ag2612");
        assert_eq!(order.status, Status::NOTTRADED);
    }
}