tigeropen 0.5.8

老虎证券 OpenAPI Rust SDK
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
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
//! 订单模型定义和构造工具函数。
//!
//! - `Order`:查询类接口返回的订单数据,使用 `#[serde(rename_all = "camelCase")]`。
//! - `OrderRequest`:下单/改单/预览订单接口的请求体,使用 `#[serde(rename_all = "snake_case")]`。

use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;

// ========== 响应模型(查询类接口返回) ==========

/// 附加订单(止盈/止损)- 响应模型
#[derive(Debug, Clone, Deserialize, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OrderLeg {
    #[serde(default)]
    pub leg_type: String,
    #[serde(default)]
    pub price: f64,
    #[serde(default)]
    pub time_in_force: String,
    #[serde(default)]
    pub quantity: i64,
}

/// 算法订单参数 - 响应模型
#[derive(Debug, Clone, Deserialize, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AlgoParams {
    #[serde(default)]
    pub algo_strategy: String,
    #[serde(default)]
    pub start_time: String,
    #[serde(default)]
    pub end_time: String,
    #[serde(default)]
    pub participation_rate: f64,
}

/// 订单响应模型。
///
/// 服务端响应字段为 camelCase。下单/改单请使用 [`OrderRequest`]。
#[derive(Debug, Clone, Deserialize, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Order {
    #[serde(default)]
    pub account: String,
    /// 全局订单 ID
    #[serde(default)]
    pub id: i64,
    /// 账户自增订单号
    #[serde(default)]
    pub order_id: i64,
    #[serde(default)]
    pub action: String,
    #[serde(default)]
    pub order_type: String,
    #[serde(default)]
    pub total_quantity: i64,
    #[serde(default)]
    pub limit_price: f64,
    #[serde(default)]
    pub aux_price: f64,
    #[serde(default)]
    pub trailing_percent: f64,
    #[serde(default, deserialize_with = "deserialize_order_status")]
    pub status: String,
    #[serde(default)]
    pub filled_quantity: i64,
    #[serde(default)]
    pub avg_fill_price: f64,
    #[serde(default)]
    pub time_in_force: String,
    #[serde(default)]
    pub outside_rth: bool,
    #[serde(default)]
    pub order_legs: Vec<OrderLeg>,
    #[serde(default)]
    pub algo_params: Option<AlgoParams>,
    #[serde(default)]
    pub symbol: String,
    #[serde(default)]
    pub sec_type: String,
    #[serde(default)]
    pub market: String,
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub expiry: String,
    #[serde(default)]
    pub strike: String,
    #[serde(default)]
    pub right: String,
    #[serde(default)]
    pub identifier: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub commission: f64,
    #[serde(default)]
    pub realized_pnl: f64,
    #[serde(default)]
    pub open_time: i64,
    #[serde(default)]
    pub update_time: i64,
    #[serde(default)]
    pub latest_time: i64,
    #[serde(default)]
    pub remark: String,
    #[serde(default)]
    pub source: String,
    #[serde(default)]
    pub user_mark: String,
    #[serde(default)]
    pub external_id: String,
    #[serde(default)]
    pub total_quantity_scale: i32,
    #[serde(default)]
    pub filled_quantity_scale: i32,
    #[serde(default)]
    pub filled_cash_amount: f64,
    #[serde(default)]
    pub gst: f64,
    #[serde(default)]
    pub liquidation: bool,
    #[serde(default)]
    pub attr_desc: String,
    #[serde(default)]
    pub attr_list: Vec<String>,
    #[serde(default)]
    pub algo_strategy: String,
    #[serde(default)]
    pub discount: f64,
    #[serde(default)]
    pub replace_status: String,
    #[serde(default)]
    pub cancel_status: String,
    #[serde(default)]
    pub can_modify: bool,
    #[serde(default)]
    pub can_cancel: bool,
    #[serde(default)]
    pub is_open: bool,
    #[serde(default)]
    pub order_discount: f64,
    #[serde(default)]
    pub trading_session_type: String,
    #[serde(default)]
    pub latest_price: f64,
    /// 冰山单:展示数量
    #[serde(default)]
    pub display_size: i64,
    /// 冰山单:最小展示数量
    #[serde(default)]
    pub min_display_size: i64,
    /// 冰山单:价检间隔(秒)
    #[serde(default)]
    pub check_intervals: i64,
    /// 冰山单:价格类型(LIMIT_PRICE / ASK_PRICE / BID_PRICE / LATEST_PRICE)
    #[serde(default)]
    pub price_type: String,
    /// 冰山单:生效开始时间(epoch ms)
    #[serde(default)]
    pub start_time: i64,
    /// 冰山单:生效结束时间(epoch ms)
    #[serde(default)]
    pub end_time: i64,
}

// ========== 自定义反序列化器 ==========

/// 处理服务端偶尔返回整数状态码的情况,将其转换为 Java SDK 枚举字符串名。
///
/// 整数映射表:-2=Invalid, -1=Initial, 3=PendingCancel, 4=Cancelled,
///             5=Submitted, 6=Filled, 7=Inactive, 8=PendingSubmit
fn deserialize_order_status<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    let v = Value::deserialize(d)?;
    match v {
        Value::String(s) => Ok(s),
        Value::Number(n) => {
            let code = n.as_i64().unwrap_or(0);
            let name = match code {
                -2 => "Invalid",
                -1 => "Initial",
                3 => "PendingCancel",
                4 => "Cancelled",
                5 => "Submitted",
                6 => "Filled",
                7 => "Inactive",
                8 => "PendingSubmit",
                _ => "Unknown",
            };
            Ok(name.to_string())
        }
        _ => Ok(String::new()),
    }
}

// ========== 请求模型(下单/改单/预览) ==========

/// 附加订单(止盈/止损)- 请求模型
#[derive(Debug, Clone, Serialize, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct OrderLegRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub leg_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quantity: Option<i64>,
}

/// MLEG 组合单子合约腿(对应 Java ContractLeg)
#[derive(Debug, Clone, Serialize, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct ContractLegRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sec_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiry: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strike: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub right: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<String>,
    /// 合约腿比例(必须大于 0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ratio: Option<i32>,
}

/// 算法订单参数 - 请求模型
#[derive(Debug, Clone, Serialize, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct AlgoParamsRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algo_strategy: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub participation_rate: Option<f64>,
}

/// 订单请求模型。
///
/// 服务端请求体字段为 snake_case。此结构体用于 `place_order` / `preview_order`
/// / `modify_order` 接口。查询返回请使用 [`Order`]。
#[derive(Debug, Clone, Serialize, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct OrderRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account: Option<String>,
    /// 全局订单 ID(修改订单时必填)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_quantity: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_price: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aux_price: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trailing_percent: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub outside_rth: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_legs: Option<Vec<OrderLegRequest>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algo_params: Option<AlgoParamsRequest>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sec_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub market: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiry: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strike: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub right: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identifier: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remark: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_mark: Option<String>,
    /// 冰山单:展示数量
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_size: Option<i64>,
    /// 冰山单:最小展示数量
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_display_size: Option<i64>,
    /// 冰山单:价检间隔(秒)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub check_intervals: Option<i64>,
    /// 冰山单:价格类型(LIMIT_PRICE / ASK_PRICE / BID_PRICE / LATEST_PRICE)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price_type: Option<String>,
    /// 冰山单:生效开始时间(epoch ms)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<i64>,
    /// 冰山单:生效结束时间(epoch ms)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<i64>,
    /// 机构账户交易密钥(client 层自动填充默认值)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secret_key: Option<String>,
    /// 限价偏移(adjust_limit),用于 STP 等场景
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adjust_limit: Option<f64>,
    /// 订单到期时间(epoch ms),GTD 单必填
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_time: Option<i64>,
    /// 交易时段类型(如 RTH / ETH / ALL)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trading_session_type: Option<String>,
    /// 交易所
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exchange: Option<String>,
    /// 合约乘数(期权/期货)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub multiplier: Option<String>,
    /// 本地合约代码
    #[serde(skip_serializing_if = "Option::is_none")]
    pub local_symbol: Option<String>,
    /// 机构分配账户列表(wire: alloc_accounts,JSON 数组)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alloc_accounts: Option<Vec<String>>,
    /// 机构分配份额列表(与 alloc_accounts 一一对应,wire: alloc_shares,JSON 数组)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alloc_shares: Option<Vec<f64>>,
    /// 数量精度(小数点后位数)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_quantity_scale: Option<i32>,
    /// 附属订单类型(PROFIT_TAKER / STOP_LOSS / BRACKET 等)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attach_type: Option<String>,
    /// 止盈订单 ID
    #[serde(
        rename = "profit_taker_orderId",
        skip_serializing_if = "Option::is_none"
    )]
    pub profit_taker_order_id: Option<i64>,
    /// 止盈价格
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profit_taker_price: Option<f64>,
    /// 止盈 TIF
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profit_taker_tif: Option<String>,
    /// 止盈是否支持盘外交易
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profit_taker_rth: Option<bool>,
    /// 止损订单类型(STP / STP LMT / TRAIL 等)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss_order_type: Option<String>,
    /// 止损订单 ID
    #[serde(rename = "stop_loss_orderId", skip_serializing_if = "Option::is_none")]
    pub stop_loss_order_id: Option<i64>,
    /// 止损触发价
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss_price: Option<f64>,
    /// 止损限价(STP LMT 用)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss_limit_price: Option<f64>,
    /// 止损 TIF
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss_tif: Option<String>,
    /// 止损追踪百分比(TRAIL 用)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss_trailing_percent: Option<f64>,
    /// 止损追踪金额(TRAIL 用)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_loss_trailing_amount: Option<f64>,
    /// 组合单类型(如 MLEG)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub combo_type: Option<String>,
    /// MLEG 多腿组合的子合约列表(wire: contract_legs,对应 Java ContractLeg)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contract_legs: Option<Vec<ContractLegRequest>>,
    /// OCA 组关联订单列表(wire: oca_orders,对应 Java List<TradeOrderModel>)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oca_orders: Option<Vec<Box<OrderRequest>>>,
    /// 现金金额(按金额下单用)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cash_amount: Option<f64>,
}

// ========== 订单请求构造工具函数 ==========

/// 构造市价单
pub fn market_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("MKT".to_string()),
        total_quantity: Some(quantity),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造限价单
pub fn limit_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    limit_price: f64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("LMT".to_string()),
        total_quantity: Some(quantity),
        limit_price: Some(limit_price),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造止损单
pub fn stop_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    aux_price: f64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("STP".to_string()),
        total_quantity: Some(quantity),
        aux_price: Some(aux_price),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造止损限价单
pub fn stop_limit_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    limit_price: f64,
    aux_price: f64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("STP_LMT".to_string()),
        total_quantity: Some(quantity),
        limit_price: Some(limit_price),
        aux_price: Some(aux_price),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造跟踪止损单
pub fn trail_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    trailing_percent: f64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("TRAIL".to_string()),
        total_quantity: Some(quantity),
        trailing_percent: Some(trailing_percent),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造竞价限价单
pub fn auction_limit_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    limit_price: f64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("AL".to_string()),
        total_quantity: Some(quantity),
        limit_price: Some(limit_price),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造竞价市价单
pub fn auction_market_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("AM".to_string()),
        total_quantity: Some(quantity),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造算法订单(TWAP/VWAP)
pub fn algo_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    limit_price: f64,
    algo_type: &str,
    params: AlgoParamsRequest,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some(algo_type.to_string()),
        total_quantity: Some(quantity),
        limit_price: Some(limit_price),
        algo_params: Some(params),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造冰山单(最简参数)
pub fn iceberg_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    limit_price: f64,
    display_size: i64,
    min_display_size: Option<i64>,
    check_intervals: Option<i64>,
    price_type: Option<&str>,
    start_time: Option<i64>,
    end_time: Option<i64>,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("ICEBERG".to_string()),
        total_quantity: Some(quantity),
        limit_price: Some(limit_price),
        time_in_force: Some("DAY".to_string()),
        display_size: Some(display_size),
        price_type: Some(price_type.unwrap_or("LIMIT_PRICE").to_string()),
        min_display_size,
        check_intervals,
        start_time: start_time.filter(|&v| v > 0),
        end_time: end_time.filter(|&v| v > 0),
        ..OrderRequest::default()
    }
}

/// 构造按金额市价单
pub fn market_order_by_amount(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    amount: f64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("MKT".to_string()),
        total_quantity: Some(0),
        cash_amount: Some(amount),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造按金额限价单
pub fn limit_order_by_amount(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    amount: f64,
    limit_price: f64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("LMT".to_string()),
        total_quantity: Some(0),
        cash_amount: Some(amount),
        limit_price: Some(limit_price),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造按价差跟踪止损单(使用 aux_price 而非百分比)
pub fn trail_order_by_price(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    aux_price: f64,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("TRAIL".to_string()),
        total_quantity: Some(quantity),
        aux_price: Some(aux_price),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造限价单 + 附加止盈/止损腿(bracket 单,最多 2 腿)
pub fn limit_order_with_legs(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    limit_price: f64,
    order_legs: Vec<OrderLegRequest>,
) -> OrderRequest {
    assert!(order_legs.len() <= 2, "At most 2 order legs are supported");
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("LMT".to_string()),
        total_quantity: Some(quantity),
        limit_price: Some(limit_price),
        order_legs: Some(order_legs),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造多腿组合单(MLEG)
pub fn combo_order(
    account: &str,
    action: &str,
    quantity: i64,
    order_type: &str,
    contract_legs: Vec<ContractLegRequest>,
    combo_type: Option<&str>,
    limit_price: Option<f64>,
    aux_price: Option<f64>,
    trailing_percent: Option<f64>,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        sec_type: Some("MLEG".to_string()),
        action: Some(action.to_string()),
        order_type: Some(order_type.to_string()),
        total_quantity: Some(quantity),
        limit_price,
        aux_price,
        trailing_percent,
        contract_legs: Some(contract_legs),
        combo_type: combo_type.map(|s| s.to_string()),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造 OCA(One-Cancels-All)单
pub fn oca_order(
    account: &str,
    symbol: &str,
    sec_type: &str,
    action: &str,
    quantity: i64,
    oca_orders: Vec<Box<OrderRequest>>,
) -> OrderRequest {
    OrderRequest {
        account: Some(account.to_string()),
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        order_type: Some("OCA".to_string()),
        total_quantity: Some(quantity),
        oca_orders: Some(oca_orders),
        time_in_force: Some("DAY".to_string()),
        ..OrderRequest::default()
    }
}

/// 构造多腿组合单的子腿
pub fn contract_leg(
    symbol: &str,
    sec_type: &str,
    action: &str,
    ratio: i32,
    expiry: Option<&str>,
    strike: Option<&str>,
    right: Option<&str>,
) -> ContractLegRequest {
    ContractLegRequest {
        symbol: Some(symbol.to_string()),
        sec_type: Some(sec_type.to_string()),
        action: Some(action.to_string()),
        ratio: Some(ratio),
        expiry: expiry.map(|s| s.to_string()),
        strike: strike.map(|s| s.to_string()),
        right: right.map(|s| s.to_string()),
    }
}

/// 构造附加订单(止盈/止损)
pub fn new_order_leg(leg_type: &str, price: f64, time_in_force: &str) -> OrderLegRequest {
    OrderLegRequest {
        leg_type: Some(leg_type.to_string()),
        price: Some(price),
        time_in_force: Some(time_in_force.to_string()),
        quantity: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_order_status_integer_deserialization() {
        // 服务端偶尔返回整数状态码
        let json = r#"{"status": 6}"#;
        let order: Order = serde_json::from_str(json).unwrap();
        assert_eq!(order.status, "Filled");

        let json = r#"{"status": 5}"#;
        let order: Order = serde_json::from_str(json).unwrap();
        assert_eq!(order.status, "Submitted");

        let json = r#"{"status": 8}"#;
        let order: Order = serde_json::from_str(json).unwrap();
        assert_eq!(order.status, "PendingSubmit");

        let json = r#"{"status": -2}"#;
        let order: Order = serde_json::from_str(json).unwrap();
        assert_eq!(order.status, "Invalid");

        // 字符串形式仍然正常工作
        let json = r#"{"status": "Filled"}"#;
        let order: Order = serde_json::from_str(json).unwrap();
        assert_eq!(order.status, "Filled");
    }

    #[test]
    fn test_order_request_serializes_to_snake_case() {
        let order = limit_order("ACC123", "AAPL", "STK", "BUY", 100, 150.50);
        let json_value: serde_json::Value = serde_json::to_value(&order).unwrap();
        let obj = json_value.as_object().unwrap();

        // snake_case 请求体
        assert!(obj.contains_key("sec_type"), "request should use sec_type");
        assert!(
            obj.contains_key("order_type"),
            "request should use order_type"
        );
        assert!(
            obj.contains_key("total_quantity"),
            "request should use total_quantity"
        );
        assert!(
            obj.contains_key("limit_price"),
            "request should use limit_price"
        );
        assert!(
            obj.contains_key("time_in_force"),
            "request should use time_in_force"
        );

        // 不应出现 camelCase
        assert!(!obj.contains_key("secType"));
        assert!(!obj.contains_key("orderType"));
        assert!(!obj.contains_key("totalQuantity"));
    }

    #[test]
    fn test_order_response_parses_camel_case() {
        let json = r#"{
            "account": "ACC123",
            "id": 42519413060422656,
            "orderId": 143,
            "action": "BUY",
            "orderType": "MKT",
            "totalQuantity": 100,
            "filledQuantity": 100,
            "avgFillPrice": 543.5,
            "timeInForce": "DAY",
            "outsideRth": false,
            "symbol": "00700",
            "secType": "STK",
            "market": "HK",
            "status": "Filled",
            "commission": 92.38,
            "realizedPnl": 0.0,
            "name": "TENCENT",
            "identifier": "00700",
            "source": "openapi",
            "userMark": "test001",
            "openTime": 1773296577000,
            "updateTime": 1773590598000
        }"#;
        let order: Order = serde_json::from_str(json).unwrap();
        assert_eq!(order.account, "ACC123");
        assert_eq!(order.id, 42519413060422656);
        assert_eq!(order.order_id, 143);
        assert_eq!(order.total_quantity, 100);
        assert_eq!(order.filled_quantity, 100);
        assert_eq!(order.avg_fill_price, 543.5);
        assert_eq!(order.status, "Filled");
        assert_eq!(order.sec_type, "STK");
        assert_eq!(order.name, "TENCENT");
        assert_eq!(order.user_mark, "test001");
        assert_eq!(order.open_time, 1773296577000);
    }

    #[test]
    fn test_market_order_helper() {
        let o = market_order("ACC", "AAPL", "STK", "BUY", 100);
        assert_eq!(o.total_quantity, Some(100));
        assert_eq!(o.order_type, Some("MKT".to_string()));
    }

    #[test]
    fn test_limit_order_helper() {
        let o = limit_order("ACC", "AAPL", "STK", "SELL", 50, 155.0);
        assert_eq!(o.order_type, Some("LMT".to_string()));
        assert_eq!(o.limit_price, Some(155.0));
    }

    #[test]
    fn test_stop_order_helper() {
        let o = stop_order("ACC", "AAPL", "STK", "SELL", 100, 140.0);
        assert_eq!(o.order_type, Some("STP".to_string()));
        assert_eq!(o.aux_price, Some(140.0));
    }

    #[test]
    fn test_new_order_leg_helper() {
        let leg = new_order_leg("PROFIT", 160.0, "GTC");
        assert_eq!(leg.leg_type, Some("PROFIT".to_string()));
        assert_eq!(leg.price, Some(160.0));
    }

    #[test]
    fn test_iceberg_order_basic() {
        let o = iceberg_order("ACC", "AAPL", "STK", "BUY", 1000, 180.0, 100, None, None, None, None, None);
        assert_eq!(o.order_type, Some("ICEBERG".to_string()));
        assert_eq!(o.total_quantity, Some(1000));
        assert_eq!(o.limit_price, Some(180.0));
        assert_eq!(o.display_size, Some(100));
        assert_eq!(o.time_in_force, Some("DAY".to_string()));
        assert_eq!(o.min_display_size, None);
        assert_eq!(o.start_time, None);
    }

    #[test]
    fn test_iceberg_order_with_optional_fields() {
        let start_time: i64 = 1782293585902;
        let end_time: i64 = 1782297185902;
        let o = iceberg_order(
            "ACC", "AAPL", "STK", "BUY", 1000, 180.0, 100,
            Some(50), Some(30), Some("LIMIT_PRICE"), Some(start_time), Some(end_time),
        );
        assert_eq!(o.order_type, Some("ICEBERG".to_string()));
        assert_eq!(o.display_size, Some(100));
        assert_eq!(o.min_display_size, Some(50));
        assert_eq!(o.check_intervals, Some(30));
        assert_eq!(o.price_type, Some("LIMIT_PRICE".to_string()));
        assert_eq!(o.start_time, Some(start_time));
        assert_eq!(o.end_time, Some(end_time));
    }

    #[test]
    fn test_iceberg_order_no_time_window() {
        let o = iceberg_order("ACC", "AAPL", "STK", "BUY", 1000, 180.0, 100, Some(50), Some(30), Some("ASK_PRICE"), None, None);
        assert_eq!(o.price_type, Some("ASK_PRICE".to_string()));
        assert_eq!(o.start_time, None);
        assert_eq!(o.end_time, None);
    }

    #[test]
    fn test_iceberg_request_serializes_snake_case() {
        let o = iceberg_order("ACC", "AAPL", "STK", "BUY", 1000, 180.0, 100, None, None, None, None, None);
        let json_value: serde_json::Value = serde_json::to_value(&o).unwrap();
        let obj = json_value.as_object().unwrap();
        assert!(
            obj.contains_key("display_size"),
            "should serialize display_size"
        );
        assert!(
            !obj.contains_key("min_display_size"),
            "None fields should be omitted"
        );
    }

    #[test]
    fn test_iceberg_response_deserializes() {
        let json = r#"{
            "orderType": "ICEBERG",
            "displaySize": 100,
            "minDisplaySize": 50,
            "checkIntervals": 30,
            "priceType": "LIMIT_PRICE",
            "startTime": 1782293585902,
            "endTime": 1782297185902
        }"#;
        let order: Order = serde_json::from_str(json).unwrap();
        assert_eq!(order.order_type, "ICEBERG");
        assert_eq!(order.display_size, 100);
        assert_eq!(order.min_display_size, 50);
        assert_eq!(order.check_intervals, 30);
        assert_eq!(order.price_type, "LIMIT_PRICE");
        assert_eq!(order.start_time, 1782293585902);
        assert_eq!(order.end_time, 1782297185902);
    }

    #[test]
    fn test_order_request_skip_none_fields() {
        let order = market_order("ACC", "AAPL", "STK", "BUY", 100);
        let json_value: serde_json::Value = serde_json::to_value(&order).unwrap();
        let obj = json_value.as_object().unwrap();

        // 必填字段存在
        assert!(obj.contains_key("symbol"));
        assert!(obj.contains_key("sec_type"));
        assert!(obj.contains_key("order_type"));
        assert!(obj.contains_key("total_quantity"));

        // None 字段不应出现
        assert!(!obj.contains_key("id"));
        assert!(!obj.contains_key("limit_price"));
        assert!(!obj.contains_key("aux_price"));
    }
}