Skip to main content

longport/trade/
types.rs

1use std::collections::BTreeMap;
2
3use num_enum::{FromPrimitive, IntoPrimitive};
4use rust_decimal::Decimal;
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use strum_macros::{Display, EnumString};
7use time::{Date, OffsetDateTime};
8
9use crate::{Market, serde_utils};
10
11/// Order type
12#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
13#[allow(clippy::upper_case_acronyms)]
14pub enum OrderType {
15    /// Unknown
16    Unknown,
17    /// Limit Order
18    #[strum(serialize = "LO")]
19    LO,
20    /// Enhanced Limit Order
21    #[strum(serialize = "ELO")]
22    ELO,
23    /// Market Order
24    #[strum(serialize = "MO")]
25    MO,
26    /// At-auction Order
27    #[strum(serialize = "AO")]
28    AO,
29    /// At-auction Limit Order
30    #[strum(serialize = "ALO")]
31    ALO,
32    /// Odd Lots
33    #[strum(serialize = "ODD")]
34    ODD,
35    /// Limit If Touched
36    #[strum(serialize = "LIT")]
37    LIT,
38    /// Market If Touched
39    #[strum(serialize = "MIT")]
40    MIT,
41    /// Trailing Limit If Touched (Trailing Amount)
42    #[strum(serialize = "TSLPAMT")]
43    TSLPAMT,
44    /// Trailing Limit If Touched (Trailing Percent)
45    #[strum(serialize = "TSLPPCT")]
46    TSLPPCT,
47    /// Trailing Market If Touched (Trailing Amount)
48    #[strum(serialize = "TSMAMT")]
49    TSMAMT,
50    /// Trailing Market If Touched (Trailing Percent)
51    #[strum(serialize = "TSMPCT")]
52    TSMPCT,
53    /// Special Limit Order
54    #[strum(serialize = "SLO")]
55    SLO,
56}
57
58/// Order status
59#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
60pub enum OrderStatus {
61    /// Unknown
62    Unknown,
63    /// Not reported
64    #[strum(serialize = "NotReported")]
65    NotReported,
66    /// Not reported (Replaced Order)
67    #[strum(serialize = "ReplacedNotReported")]
68    ReplacedNotReported,
69    /// Not reported (Protected Order)
70    #[strum(serialize = "ProtectedNotReported")]
71    ProtectedNotReported,
72    /// Not reported (Conditional Order)
73    #[strum(serialize = "VarietiesNotReported")]
74    VarietiesNotReported,
75    /// Filled
76    #[strum(serialize = "FilledStatus")]
77    Filled,
78    /// Wait To New
79    #[strum(serialize = "WaitToNew")]
80    WaitToNew,
81    /// New
82    #[strum(serialize = "NewStatus")]
83    New,
84    /// Wait To Replace
85    #[strum(serialize = "WaitToReplace")]
86    WaitToReplace,
87    /// Pending Replace
88    #[strum(serialize = "PendingReplaceStatus")]
89    PendingReplace,
90    /// Replaced
91    #[strum(serialize = "ReplacedStatus")]
92    Replaced,
93    /// Partial Filled
94    #[strum(serialize = "PartialFilledStatus")]
95    PartialFilled,
96    /// Wait To Cancel
97    #[strum(serialize = "WaitToCancel")]
98    WaitToCancel,
99    /// Pending Cancel
100    #[strum(serialize = "PendingCancelStatus")]
101    PendingCancel,
102    /// Rejected
103    #[strum(serialize = "RejectedStatus")]
104    Rejected,
105    /// Canceled
106    #[strum(serialize = "CanceledStatus")]
107    Canceled,
108    /// Expired
109    #[strum(serialize = "ExpiredStatus")]
110    Expired,
111    /// Partial Withdrawal
112    #[strum(serialize = "PartialWithdrawal")]
113    PartialWithdrawal,
114    /// Monitoring (Time-Conditional Order)
115    #[strum(serialize = "DelayedNotReported")]
116    DelayedNotReported,
117}
118
119/// Execution
120#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct Execution {
122    /// Order ID
123    pub order_id: String,
124    /// Execution ID
125    pub trade_id: String,
126    /// Security code
127    pub symbol: String,
128    /// Trade done time
129    #[serde(
130        serialize_with = "time::serde::rfc3339::serialize",
131        deserialize_with = "serde_utils::timestamp::deserialize"
132    )]
133    pub trade_done_at: OffsetDateTime,
134    /// Executed quantity
135    pub quantity: Decimal,
136    /// Executed price
137    pub price: Decimal,
138    /// Order side. `Unknown` when the response omits it, as
139    /// `/v1/trade/execution/history` does for LongPort US accounts.
140    #[serde(default)]
141    pub side: OrderSide,
142}
143
144/// Response for get all executions request
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct AllExecutionsResponse {
147    /// Has more records
148    pub has_more: bool,
149    /// Execution list
150    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
151    pub trades: Vec<Execution>,
152}
153
154/// Order side
155#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
156pub enum OrderSide {
157    /// Unknown
158    Unknown,
159    /// Buy
160    #[strum(serialize = "Buy")]
161    Buy,
162    /// Sell
163    #[strum(serialize = "Sell")]
164    Sell,
165}
166
167/// Order trigger price type
168#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
169pub enum TriggerPriceType {
170    /// Unknown
171    Unknown,
172    /// Limit If Touched
173    #[strum(serialize = "LIT")]
174    LimitIfTouched,
175    /// Market If Touched
176    #[strum(serialize = "MIT")]
177    MarketIfTouched,
178}
179
180/// Order tag
181#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
182pub enum OrderTag {
183    /// Unknown
184    Unknown,
185    /// Normal Order
186    #[strum(serialize = "Normal")]
187    Normal,
188    /// Long term Order
189    #[strum(serialize = "Gtc")]
190    LongTerm,
191    /// Grey Order
192    #[strum(serialize = "Grey")]
193    Grey,
194}
195
196/// Time in force Type
197#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
198pub enum TimeInForceType {
199    /// Unknown
200    Unknown,
201    /// Day Order
202    #[strum(serialize = "Day")]
203    Day,
204    /// Good Til Canceled Order
205    #[strum(serialize = "GTC")]
206    GoodTilCanceled,
207    /// Good Til Date Order
208    #[strum(serialize = "GTD")]
209    GoodTilDate,
210}
211
212/// Trigger status
213#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
214pub enum TriggerStatus {
215    /// Unknown
216    Unknown,
217    /// Deactive
218    #[strum(serialize = "DEACTIVE")]
219    Deactive,
220    /// Active
221    #[strum(serialize = "ACTIVE")]
222    Active,
223    /// Released
224    #[strum(serialize = "RELEASED")]
225    Released,
226}
227
228/// Enable or disable outside regular trading hours
229#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
230pub enum OutsideRTH {
231    /// Unknown
232    Unknown,
233    /// Regular trading hour only
234    #[strum(serialize = "RTH_ONLY")]
235    RTHOnly,
236    /// Any time
237    #[strum(serialize = "ANY_TIME")]
238    AnyTime,
239    /// Overnight
240    #[strum(serialize = "OVERNIGHT")]
241    Overnight,
242    /// Overnight option
243    #[strum(serialize = "OPTION_PRE_MARKET")]
244    OptionPreMarket,
245}
246
247/// Attached order type
248#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
249pub enum AttachedOrderType {
250    /// Unknown
251    Unknown,
252    /// Take profit
253    #[strum(serialize = "PROFIT_TAKER")]
254    ProfitTaker,
255    /// Stop loss
256    #[strum(serialize = "STOP_LOSS")]
257    StopLoss,
258    /// Bracket order
259    #[strum(serialize = "BRACKET")]
260    Bracket,
261}
262
263/// Attached order detail
264#[derive(Debug, Clone, Serialize, Deserialize)]
265pub struct AttachedOrderDetail {
266    /// Attached order ID
267    pub order_id: String,
268    /// Attached order type
269    pub attached_type_display: AttachedOrderType,
270    /// Trigger price
271    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
272    pub trigger_price: Option<Decimal>,
273    /// Quantity
274    pub quantity: Decimal,
275    /// Executed quantity
276    pub executed_qty: Decimal,
277    /// Order status
278    pub status: OrderStatus,
279    /// Last updated time (unix timestamp seconds)
280    #[serde(
281        serialize_with = "time::serde::rfc3339::serialize",
282        deserialize_with = "serde_utils::timestamp::deserialize"
283    )]
284    pub updated_at: OffsetDateTime,
285    /// Whether withdrawn
286    pub withdrawn: bool,
287    /// GTD date
288    #[serde(with = "serde_utils::date_opt")]
289    pub gtd: Option<Date>,
290    /// Time in force
291    pub time_in_force: TimeInForceType,
292    /// Counter order ID
293    pub counter_id: String,
294    /// Trigger status
295    #[serde(with = "serde_utils::trigger_status")]
296    pub trigger_status: Option<TriggerStatus>,
297    /// Executed amount
298    pub executed_amount: Decimal,
299    /// Tag
300    pub tag: OrderTag,
301    /// Submitted time (unix timestamp seconds)
302    #[serde(
303        serialize_with = "time::serde::rfc3339::serialize",
304        deserialize_with = "serde_utils::timestamp::deserialize"
305    )]
306    pub submitted_at: OffsetDateTime,
307    /// Executed price
308    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
309    pub executed_price: Option<Decimal>,
310    /// Force RTH only
311    #[serde(with = "serde_utils::outside_rth")]
312    pub force_only_rth: Option<OutsideRTH>,
313    /// Whether reviewed
314    pub reviewed: bool,
315    /// Order type to submit after trigger
316    pub activate_order_type: OrderType,
317    /// RTH setting for activated order
318    #[serde(with = "serde_utils::outside_rth")]
319    pub activate_rth: Option<OutsideRTH>,
320    /// Submit price (limit price)
321    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
322    pub submit_price: Option<Decimal>,
323    /// Bid/ask depth level of the limit order submitted price
324    #[serde(
325        default,
326        deserialize_with = "serde_utils::int32_opt_null_or_0_is_none::deserialize",
327        serialize_with = "serde_utils::int32_opt_0_is_none::serialize"
328    )]
329    pub limit_depth_level: Option<i32>,
330}
331
332/// Multi-leg strategy
333#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
334pub enum MultiLegStrategy {
335    /// Unknown
336    Unknown,
337    /// Covered call (covered stock)
338    #[strum(to_string = "CoveredCall", serialize = "0")]
339    CoveredCall,
340    /// Covered put (covered stock)
341    #[strum(to_string = "CoveredPut", serialize = "1")]
342    CoveredPut,
343    /// Vertical call spread
344    #[strum(to_string = "VerticalCallSpread", serialize = "2")]
345    VerticalCallSpread,
346    /// Vertical put spread
347    #[strum(to_string = "VerticalPutSpread", serialize = "3")]
348    VerticalPutSpread,
349    /// Collar
350    #[strum(to_string = "Collar", serialize = "4")]
351    Collar,
352    /// Straddle
353    #[strum(to_string = "Straddle", serialize = "5")]
354    Straddle,
355    /// Strangle
356    #[strum(to_string = "Strangle", serialize = "6")]
357    Strangle,
358    /// Calendar call spread
359    #[strum(to_string = "CalendarCallSpread", serialize = "7")]
360    CalendarCallSpread,
361    /// Calendar put spread
362    #[strum(to_string = "CalendarPutSpread", serialize = "8")]
363    CalendarPutSpread,
364}
365
366/// Multi-leg position direction
367#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
368pub enum MultiLegPosition {
369    /// Unknown
370    Unknown,
371    /// Long
372    #[strum(serialize = "LONG")]
373    Long,
374    /// Short
375    #[strum(serialize = "SHORT")]
376    Short,
377}
378
379/// Option contract type
380#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
381pub enum ContractDirection {
382    /// Unknown
383    Unknown,
384    /// Call
385    #[strum(serialize = "C")]
386    Call,
387    /// Put
388    #[strum(serialize = "P")]
389    Put,
390}
391
392/// A leg of a multi-leg combination order
393#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct MultiLegOrderLeg {
395    /// Option symbol, in `ticker.region` format
396    pub symbol: String,
397    /// Order side
398    pub side: OrderSide,
399    /// Position direction
400    pub position: MultiLegPosition,
401    /// Leg ratio quantity
402    #[serde(with = "serde_utils::decimal_empty_is_0")]
403    pub ratio_quantity: Decimal,
404    /// Strike price
405    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
406    pub strike_price: Option<Decimal>,
407    /// Option expiry date
408    #[serde(default, with = "serde_utils::date_ymd_opt")]
409    pub expire_date: Option<Date>,
410    /// Contract type
411    pub contract_direction: ContractDirection,
412}
413
414/// Multi-leg strategy information
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct MultiLegInfo {
417    /// Multi-leg strategy
418    pub strategy: MultiLegStrategy,
419    /// Strategy name
420    pub strategy_name: String,
421    /// Multi-leg combination ID
422    pub multileg_id: String,
423    /// Multi-leg combination code
424    pub code: String,
425    /// Legs of the combination order
426    #[serde(default)]
427    pub legs: Vec<MultiLegOrderLeg>,
428}
429
430/// Order
431#[derive(Debug, Clone, Serialize, Deserialize)]
432pub struct Order {
433    /// Order ID
434    pub order_id: String,
435    /// Order status
436    pub status: OrderStatus,
437    /// Stock name
438    pub stock_name: String,
439    /// Submitted quantity
440    pub quantity: Decimal,
441    /// Executed quantity
442    pub executed_quantity: Decimal,
443    /// Submitted price
444    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
445    pub price: Option<Decimal>,
446    /// Executed price
447    #[serde(with = "serde_utils::decimal_opt_0_is_none")]
448    pub executed_price: Option<Decimal>,
449    /// Submitted time
450    #[serde(
451        serialize_with = "time::serde::rfc3339::serialize",
452        deserialize_with = "serde_utils::timestamp::deserialize"
453    )]
454    pub submitted_at: OffsetDateTime,
455    /// Order side
456    pub side: OrderSide,
457    /// Security code
458    pub symbol: String,
459    /// Order type
460    pub order_type: OrderType,
461    /// Last done
462    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
463    pub last_done: Option<Decimal>,
464    /// `LIT` / `MIT` Order Trigger Price
465    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
466    pub trigger_price: Option<Decimal>,
467    /// Rejected Message or remark
468    pub msg: String,
469    /// Order tag
470    pub tag: OrderTag,
471    /// Time in force type
472    pub time_in_force: TimeInForceType,
473    /// Long term order expire date
474    #[serde(with = "serde_utils::date_opt")]
475    pub expire_date: Option<Date>,
476    /// Last updated time
477    #[serde(
478        deserialize_with = "serde_utils::timestamp_opt::deserialize",
479        serialize_with = "serde_utils::rfc3339_opt::serialize"
480    )]
481    pub updated_at: Option<OffsetDateTime>,
482    /// Conditional order trigger time
483    #[serde(
484        deserialize_with = "serde_utils::timestamp_opt::deserialize",
485        serialize_with = "serde_utils::rfc3339_opt::serialize"
486    )]
487    pub trigger_at: Option<OffsetDateTime>,
488    /// `TSMAMT` / `TSLPAMT` order trailing amount
489    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
490    pub trailing_amount: Option<Decimal>,
491    /// `TSMPCT` / `TSLPPCT` order trailing percent
492    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
493    pub trailing_percent: Option<Decimal>,
494    /// `TSLPAMT` / `TSLPPCT` order limit offset amount
495    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
496    pub limit_offset: Option<Decimal>,
497    /// Conditional order trigger status
498    #[serde(with = "serde_utils::trigger_status")]
499    pub trigger_status: Option<TriggerStatus>,
500    /// Currency
501    pub currency: String,
502    /// Enable or disable outside regular trading hours
503    #[serde(with = "serde_utils::outside_rth")]
504    pub outside_rth: Option<OutsideRTH>,
505    /// Limit depth level
506    #[serde(with = "serde_utils::int32_opt_0_is_none")]
507    pub limit_depth_level: Option<i32>,
508    /// Trigger count
509    #[serde(with = "serde_utils::int32_opt_0_is_none")]
510    pub trigger_count: Option<i32>,
511    /// Monitor price
512    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
513    pub monitor_price: Option<Decimal>,
514    /// Remark
515    pub remark: String,
516    /// Time-condition submit time (`None` when the order is not a
517    /// time-condition order)
518    #[serde(
519        default,
520        deserialize_with = "serde_utils::timestamp_opt_lenient::deserialize",
521        serialize_with = "serde_utils::rfc3339_opt::serialize"
522    )]
523    pub delayed_until: Option<OffsetDateTime>,
524    /// Attached orders
525    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
526    pub attached_orders: Vec<AttachedOrderDetail>,
527    /// Multi-leg strategy information (only present for multi-leg option
528    /// combination orders)
529    #[serde(default)]
530    pub multi_leg: Option<MultiLegInfo>,
531}
532
533/// Commission-free Status
534#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
535pub enum CommissionFreeStatus {
536    /// Unknown
537    Unknown,
538    /// None
539    None,
540    /// Commission-free amount to be calculated
541    Calculated,
542    /// Pending commission-free
543    Pending,
544    /// Commission-free applied
545    Ready,
546}
547
548/// Deduction status
549#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
550pub enum DeductionStatus {
551    /// Unknown
552    Unknown,
553    /// Pending Settlement
554    #[strum(serialize = "NONE")]
555    None,
556    /// Settled with no data
557    #[strum(serialize = "NO_DATA")]
558    NoData,
559    /// Settled and pending distribution
560    #[strum(serialize = "PENDING")]
561    Pending,
562    /// Settled and distributed
563    #[strum(serialize = "DONE")]
564    Done,
565}
566
567/// Charge category code
568#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
569pub enum ChargeCategoryCode {
570    /// Unknown
571    Unknown,
572    /// Broker
573    #[strum(serialize = "BROKER_FEES")]
574    Broker,
575    /// Third
576    #[strum(serialize = "THIRD_FEES")]
577    Third,
578}
579
580/// Order history detail
581#[derive(Debug, Clone, Serialize, Deserialize)]
582pub struct OrderHistoryDetail {
583    /// Executed price for executed orders, submitted price for expired,
584    /// canceled, rejected orders, etc.
585    #[serde(with = "serde_utils::decimal_empty_is_0")]
586    pub price: Decimal,
587    /// Executed quantity for executed orders, remaining quantity for expired,
588    /// canceled, rejected orders, etc.
589    #[serde(with = "serde_utils::decimal_empty_is_0")]
590    pub quantity: Decimal,
591    /// Order status
592    pub status: OrderStatus,
593    /// Execution or error message
594    pub msg: String,
595    /// Occurrence time
596    #[serde(
597        serialize_with = "time::serde::rfc3339::serialize",
598        deserialize_with = "serde_utils::timestamp::deserialize"
599    )]
600    pub time: OffsetDateTime,
601}
602
603/// Order charge fee
604#[derive(Debug, Clone, Serialize, Deserialize)]
605pub struct OrderChargeFee {
606    /// Charge code
607    pub code: String,
608    /// Charge name
609    pub name: String,
610    /// Charge amount
611    #[serde(with = "serde_utils::decimal_empty_is_0")]
612    pub amount: Decimal,
613    /// Charge currency
614    pub currency: String,
615}
616
617/// Order charge item
618#[derive(Debug, Clone, Serialize, Deserialize)]
619pub struct OrderChargeItem {
620    /// Charge category code
621    pub code: ChargeCategoryCode,
622    /// Charge category name
623    pub name: String,
624    /// Charge details
625    pub fees: Vec<OrderChargeFee>,
626}
627
628/// Order charge detail
629#[derive(Debug, Clone, Serialize, Deserialize)]
630pub struct OrderChargeDetail {
631    /// Total charges amount
632    pub total_amount: Decimal,
633    /// Settlement currency
634    pub currency: String,
635    /// Order charge items
636    pub items: Vec<OrderChargeItem>,
637}
638
639/// Order detail
640#[derive(Debug, Clone, Serialize, Deserialize)]
641pub struct OrderDetail {
642    /// Order ID
643    pub order_id: String,
644    /// Order status
645    pub status: OrderStatus,
646    /// Stock name
647    pub stock_name: String,
648    /// Submitted quantity
649    pub quantity: Decimal,
650    /// Executed quantity
651    pub executed_quantity: Decimal,
652    /// Submitted price
653    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
654    pub price: Option<Decimal>,
655    /// Executed price
656    #[serde(with = "serde_utils::decimal_opt_0_is_none")]
657    pub executed_price: Option<Decimal>,
658    /// Submitted time
659    #[serde(
660        serialize_with = "time::serde::rfc3339::serialize",
661        deserialize_with = "serde_utils::timestamp::deserialize"
662    )]
663    pub submitted_at: OffsetDateTime,
664    /// Order side
665    pub side: OrderSide,
666    /// Security code
667    pub symbol: String,
668    /// Order type
669    pub order_type: OrderType,
670    /// Last done
671    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
672    pub last_done: Option<Decimal>,
673    /// `LIT` / `MIT` Order Trigger Price
674    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
675    pub trigger_price: Option<Decimal>,
676    /// Rejected Message or remark
677    pub msg: String,
678    /// Order tag
679    pub tag: OrderTag,
680    /// Time in force type
681    pub time_in_force: TimeInForceType,
682    /// Long term order expire date
683    #[serde(with = "serde_utils::date_opt")]
684    pub expire_date: Option<Date>,
685    /// Last updated time
686    #[serde(
687        deserialize_with = "serde_utils::timestamp_opt::deserialize",
688        serialize_with = "serde_utils::rfc3339_opt::serialize"
689    )]
690    pub updated_at: Option<OffsetDateTime>,
691    /// Conditional order trigger time
692    #[serde(
693        deserialize_with = "serde_utils::timestamp_opt::deserialize",
694        serialize_with = "serde_utils::rfc3339_opt::serialize"
695    )]
696    pub trigger_at: Option<OffsetDateTime>,
697    /// `TSMAMT` / `TSLPAMT` order trailing amount
698    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
699    pub trailing_amount: Option<Decimal>,
700    /// `TSMPCT` / `TSLPPCT` order trailing percent
701    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
702    pub trailing_percent: Option<Decimal>,
703    /// `TSLPAMT` / `TSLPPCT` order limit offset amount
704    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
705    pub limit_offset: Option<Decimal>,
706    /// Conditional order trigger status
707    #[serde(with = "serde_utils::trigger_status")]
708    pub trigger_status: Option<TriggerStatus>,
709    /// Currency
710    pub currency: String,
711    /// Enable or disable outside regular trading hours
712    #[serde(with = "serde_utils::outside_rth")]
713    pub outside_rth: Option<OutsideRTH>,
714    /// Limit depth level
715    #[serde(with = "serde_utils::int32_opt_0_is_none")]
716    pub limit_depth_level: Option<i32>,
717    /// Trigger count
718    #[serde(with = "serde_utils::int32_opt_0_is_none")]
719    pub trigger_count: Option<i32>,
720    /// Monitor price
721    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
722    pub monitor_price: Option<Decimal>,
723    /// Remark
724    pub remark: String,
725    /// Time-condition submit time (`None` when the order is not a
726    /// time-condition order)
727    #[serde(
728        default,
729        deserialize_with = "serde_utils::timestamp_opt_lenient::deserialize",
730        serialize_with = "serde_utils::rfc3339_opt::serialize"
731    )]
732    pub delayed_until: Option<OffsetDateTime>,
733    /// Commission-free Status
734    pub free_status: CommissionFreeStatus,
735    /// Commission-free amount
736    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
737    pub free_amount: Option<Decimal>,
738    /// Commission-free currency
739    #[serde(with = "serde_utils::symbol_opt")]
740    pub free_currency: Option<String>,
741    /// Deduction status
742    pub deductions_status: DeductionStatus,
743    /// Deduction amount
744    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
745    pub deductions_amount: Option<Decimal>,
746    /// Deduction currency
747    #[serde(with = "serde_utils::symbol_opt")]
748    pub deductions_currency: Option<String>,
749    /// Platform fee deduction status
750    pub platform_deducted_status: DeductionStatus,
751    /// Platform deduction amount
752    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
753    pub platform_deducted_amount: Option<Decimal>,
754    /// Platform deduction currency
755    #[serde(with = "serde_utils::symbol_opt")]
756    pub platform_deducted_currency: Option<String>,
757    /// Order history details
758    pub history: Vec<OrderHistoryDetail>,
759    /// Order charges
760    pub charge_detail: Option<OrderChargeDetail>,
761    /// Attached orders
762    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
763    pub attached_orders: Vec<AttachedOrderDetail>,
764    /// Multi-leg strategy information (only present for multi-leg option
765    /// combination orders)
766    #[serde(default)]
767    pub multi_leg: Option<MultiLegInfo>,
768}
769
770/// Cash info
771#[derive(Debug, Clone, Serialize, Deserialize)]
772pub struct CashInfo {
773    /// Withdraw cash
774    pub withdraw_cash: Decimal,
775    /// Available cash
776    pub available_cash: Decimal,
777    /// Frozen cash
778    pub frozen_cash: Decimal,
779    /// Cash to be settled
780    pub settling_cash: Decimal,
781    /// Currency
782    pub currency: String,
783}
784
785/// Frozen transaction fee
786#[derive(Debug, Clone, Serialize, Deserialize)]
787pub struct FrozenTransactionFee {
788    /// Currency
789    pub currency: String,
790    /// Frozen transaction fee amount
791    pub frozen_transaction_fee: Decimal,
792}
793
794/// Account balance
795#[derive(Debug, Clone, Serialize, Deserialize)]
796pub struct AccountBalance {
797    /// Total cash
798    pub total_cash: Decimal,
799    /// Maximum financing amount
800    pub max_finance_amount: Decimal,
801    /// Remaining financing amount
802    pub remaining_finance_amount: Decimal,
803    /// Risk control level
804    #[serde(with = "serde_utils::risk_level")]
805    pub risk_level: i32,
806    /// Margin call
807    pub margin_call: Decimal,
808    /// Currency
809    pub currency: String,
810    /// Cash details
811    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
812    pub cash_infos: Vec<CashInfo>,
813    /// Net assets
814    #[serde(with = "serde_utils::decimal_empty_is_0")]
815    pub net_assets: Decimal,
816    /// Initial margin
817    #[serde(with = "serde_utils::decimal_empty_is_0")]
818    pub init_margin: Decimal,
819    /// Maintenance margin
820    #[serde(with = "serde_utils::decimal_empty_is_0")]
821    pub maintenance_margin: Decimal,
822    /// Buy power
823    #[serde(with = "serde_utils::decimal_empty_is_0")]
824    pub buy_power: Decimal,
825    /// Frozen transaction fees
826    pub frozen_transaction_fees: Vec<FrozenTransactionFee>,
827}
828
829/// Balance type
830#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, FromPrimitive, IntoPrimitive)]
831#[repr(i32)]
832pub enum BalanceType {
833    /// Unknown
834    #[num_enum(default)]
835    Unknown = 0,
836    /// Cash
837    Cash = 1,
838    /// Stock
839    Stock = 2,
840    /// Fund
841    Fund = 3,
842}
843
844impl Serialize for BalanceType {
845    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
846        let value: i32 = (*self).into();
847        value.serialize(serializer)
848    }
849}
850
851impl<'de> Deserialize<'de> for BalanceType {
852    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
853        let value = i32::deserialize(deserializer)?;
854        Ok(BalanceType::from(value))
855    }
856}
857
858/// Cash flow direction
859#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, FromPrimitive, Serialize)]
860#[repr(i32)]
861pub enum CashFlowDirection {
862    /// Unknown
863    #[num_enum(default)]
864    Unknown,
865    /// Out
866    Out = 1,
867    /// In
868    In = 2,
869}
870
871impl<'de> Deserialize<'de> for CashFlowDirection {
872    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
873        let value = i32::deserialize(deserializer)?;
874        Ok(CashFlowDirection::from(value))
875    }
876}
877
878/// Cash flow
879#[derive(Debug, Clone, Serialize, Deserialize)]
880pub struct CashFlow {
881    /// Cash flow name
882    pub transaction_flow_name: String,
883    /// Outflow direction
884    pub direction: CashFlowDirection,
885    /// Balance type
886    pub business_type: BalanceType,
887    /// Cash amount
888    pub balance: Decimal,
889    /// Cash currency
890    pub currency: String,
891    /// Business time
892    #[serde(
893        serialize_with = "time::serde::rfc3339::serialize",
894        deserialize_with = "serde_utils::timestamp::deserialize"
895    )]
896    pub business_time: OffsetDateTime,
897    /// Associated Stock code information
898    #[serde(with = "serde_utils::symbol_opt")]
899    pub symbol: Option<String>,
900    /// Cash flow description
901    pub description: String,
902}
903
904/// Fund positions response
905#[derive(Debug, Clone, Serialize, Deserialize)]
906pub struct FundPositionsResponse {
907    /// Channels
908    #[serde(rename = "list")]
909    pub channels: Vec<FundPositionChannel>,
910}
911
912/// Fund position channel
913#[derive(Debug, Clone, Serialize, Deserialize)]
914pub struct FundPositionChannel {
915    /// Account type
916    pub account_channel: String,
917
918    /// Fund positions
919    #[serde(
920        default,
921        deserialize_with = "crate::serde_utils::null_as_default",
922        rename = "fund_info"
923    )]
924    pub positions: Vec<FundPosition>,
925}
926
927/// Fund position
928#[derive(Debug, Clone, Serialize, Deserialize)]
929pub struct FundPosition {
930    /// Fund counter id (the ISIN is the last `/`-separated segment)
931    #[serde(alias = "symbol")]
932    pub counter_id: String,
933    /// Current equity
934    #[serde(with = "serde_utils::decimal_empty_is_0")]
935    pub current_net_asset_value: Decimal,
936    /// Current equity time
937    #[serde(
938        serialize_with = "time::serde::rfc3339::serialize",
939        deserialize_with = "serde_utils::timestamp::deserialize"
940    )]
941    pub net_asset_value_day: OffsetDateTime,
942    /// Fund name
943    pub symbol_name: String,
944    /// Currency
945    pub currency: String,
946    /// Net cost
947    #[serde(with = "serde_utils::decimal_empty_is_0")]
948    pub cost_net_asset_value: Decimal,
949    /// Holding units
950    #[serde(with = "serde_utils::decimal_empty_is_0")]
951    pub holding_units: Decimal,
952}
953
954/// Stock positions response
955#[derive(Debug, Clone, Serialize, Deserialize)]
956pub struct StockPositionsResponse {
957    /// Channels
958    #[serde(rename = "list")]
959    pub channels: Vec<StockPositionChannel>,
960}
961
962/// Stock position channel
963#[derive(Debug, Clone, Serialize, Deserialize)]
964pub struct StockPositionChannel {
965    /// Account type
966    pub account_channel: String,
967
968    /// Stock positions
969    #[serde(
970        default,
971        deserialize_with = "crate::serde_utils::null_as_default",
972        rename = "stock_info"
973    )]
974    pub positions: Vec<StockPosition>,
975}
976
977/// Stock position
978#[derive(Debug, Clone, Serialize, Deserialize)]
979pub struct StockPosition {
980    /// Stock code
981    pub symbol: String,
982    /// Stock name
983    pub symbol_name: String,
984    /// The number of holdings
985    pub quantity: Decimal,
986    /// Available quantity
987    pub available_quantity: Decimal,
988    /// Currency
989    pub currency: String,
990    /// Cost Price(According to the client's choice of average purchase or
991    /// diluted cost)
992    #[serde(with = "serde_utils::decimal_empty_is_0")]
993    pub cost_price: Decimal,
994    /// Market
995    pub market: Market,
996    /// Initial position before market opening
997    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
998    pub init_quantity: Option<Decimal>,
999}
1000
1001/// Margin ratio
1002#[derive(Debug, Clone, Serialize, Deserialize)]
1003pub struct MarginRatio {
1004    /// Initial margin ratio
1005    pub im_factor: Decimal,
1006    /// Maintain the initial margin ratio
1007    pub mm_factor: Decimal,
1008    /// Forced close-out margin ratio
1009    pub fm_factor: Decimal,
1010}
1011
1012/// Risk assessment (suitability questionnaire) result of the current member
1013///
1014/// Mirrors the server response of `GET /v1/members/me/risk-assessment`
1015/// field-for-field. Decoding is lenient: integers are accepted as JSON integers
1016/// or integer strings (anything else becomes 0), string fields render
1017/// non-string values as JSON text (null becomes empty), and a map or list
1018/// field holding anything other than an object / array (e.g. null, or `[]` for
1019/// a map) becomes empty.
1020#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1021pub struct RiskAssessment {
1022    /// Risk level of the latest questionnaire (e.g. `A5`).
1023    ///
1024    /// The server does not document the scale, so do not infer an ordering
1025    /// between levels; report the value as-is. May be empty; the server does
1026    /// not document when.
1027    #[serde(default, deserialize_with = "serde_utils::string_lenient")]
1028    pub risk: String,
1029    /// Professional investor (PI) status code, as returned by the server.
1030    ///
1031    /// The server does not document the code values; treat it as an opaque
1032    /// identifier rather than inferring an ordering from it.
1033    #[serde(default, deserialize_with = "serde_utils::int32_lenient")]
1034    pub pi: i32,
1035    /// Approval states keyed by item (e.g. `car`, `cka`, `risk_audit`,
1036    /// `is_corporate_client`).
1037    ///
1038    /// Values are the server's strings, not booleans: `is_corporate_client`
1039    /// arrives as `"true"` / `"false"`, so compare the string rather than
1040    /// testing it for truthiness.
1041    #[serde(default, deserialize_with = "serde_utils::string_map_lenient")]
1042    pub approvals: BTreeMap<String, String>,
1043    /// Re-authentication flag, as returned by the server (empty when not set)
1044    #[serde(default, deserialize_with = "serde_utils::string_lenient")]
1045    pub re_authentication: String,
1046    /// Professional investor status end time, as returned by the server (`0`
1047    /// when not set).
1048    ///
1049    /// Deliberately left as the raw integer: the server does not document the
1050    /// unit (seconds or milliseconds), so the SDK does not convert it to a
1051    /// timestamp the way other `*_at` fields are converted. Confirm the unit
1052    /// with the gateway before interpreting a non-zero value.
1053    #[serde(default, deserialize_with = "serde_utils::int64_lenient")]
1054    pub pi_end_at: i64,
1055    /// Deadlines keyed by item, as returned by the server.
1056    ///
1057    /// Raw integers, with the same undocumented unit as [`Self::pi_end_at`].
1058    #[serde(default, deserialize_with = "serde_utils::int64_map_lenient")]
1059    pub deadlines: BTreeMap<String, i64>,
1060    /// Date of the latest risk assessment, as returned by the server (e.g.
1061    /// `2026-10-14`).
1062    ///
1063    /// Kept as the server's string rather than a `Date`: the server is not
1064    /// documented to guarantee the `yyyy-mm-dd` form. May be empty; a null or
1065    /// absent value also decodes to an empty string, so emptiness does not by
1066    /// itself mean "never assessed".
1067    #[serde(default, deserialize_with = "serde_utils::string_lenient")]
1068    pub risk_assessment_at: String,
1069    /// Questionnaire score
1070    #[serde(default, deserialize_with = "serde_utils::int32_lenient")]
1071    pub score: i32,
1072    /// Strategy risk levels of the member. The server does not document what
1073    /// these levels permit, so do not read them as a trading entitlement.
1074    #[serde(default, deserialize_with = "serde_utils::string_vec_lenient")]
1075    pub strategy_risk_levels: Vec<String>,
1076}
1077
1078impl_serde_for_enum_string!(
1079    OrderType,
1080    OrderStatus,
1081    OrderSide,
1082    TriggerPriceType,
1083    OrderTag,
1084    TimeInForceType,
1085    TriggerStatus,
1086    OutsideRTH,
1087    CommissionFreeStatus,
1088    DeductionStatus,
1089    ChargeCategoryCode
1090);
1091impl_serde_for_enum_string!(AttachedOrderType);
1092impl_default_for_enum_string!(AttachedOrderType);
1093impl_serde_for_enum_string!(MultiLegStrategy, MultiLegPosition, ContractDirection);
1094impl_default_for_enum_string!(MultiLegStrategy, MultiLegPosition, ContractDirection);
1095impl_default_for_enum_string!(
1096    OrderType,
1097    OrderStatus,
1098    OrderSide,
1099    TriggerPriceType,
1100    OrderTag,
1101    TimeInForceType,
1102    TriggerStatus,
1103    OutsideRTH,
1104    CommissionFreeStatus,
1105    DeductionStatus,
1106    ChargeCategoryCode
1107);
1108
1109// ── US-market types
1110// ───────────────────────────────────────────────────────────
1111
1112/// Request for [`crate::TradeContext::us_query_orders`], modelled after
1113/// [`crate::GetHistoryOrdersOptions`] for HK/CN orders.
1114///
1115/// `query_type`: 0 = all (includes Rejected), 1 = pending, 2 = history (filled
1116/// only). Default 0 matches what the app shows as "past orders".
1117///
1118/// `symbol` accepts a user-facing symbol e.g. `"AAPL.US"` or `"DOGEUSD.BKKT"`
1119/// and is sent to the server as-is.
1120#[derive(Debug, Clone, Default)]
1121pub struct GetUSHistoryOrders {
1122    /// Optional symbol filter, e.g. `"AAPL.US"`.
1123    pub symbol: Option<String>,
1124    /// Direction filter. [`crate::OrderSide::Unknown`] = all (default).
1125    pub side: OrderSide,
1126    /// Start timestamp (seconds). Defaults to 90 days ago.
1127    pub start_at: i64,
1128    /// End timestamp (seconds). Defaults to now.
1129    pub end_at: i64,
1130    /// 0 = all, 1 = pending, 2 = history (filled only). Default 0.
1131    pub query_type: i32,
1132    /// Page number, 1-based. Default 1.
1133    pub page: i32,
1134    /// Page size. Default 20.
1135    pub limit: i32,
1136}
1137
1138/// Alias kept for backward compatibility.
1139pub type QueryUSOrdersOptions = GetUSHistoryOrders;
1140
1141/// Internal JSON body sent to POST /v1/us/orders/query.
1142#[derive(Debug, Clone, Serialize)]
1143pub(crate) struct USQueryOrdersBody {
1144    pub account_channel: String,
1145    pub action: i32,
1146    pub start_at: f64,
1147    pub end_at: f64,
1148    pub symbols: Vec<String>,
1149    pub security_types: Vec<String>,
1150    pub query_type: i32,
1151    pub page: i32,
1152    pub limit: i32,
1153    pub query_version: f64,
1154}
1155
1156/// Response for [`crate::TradeContext::us_query_orders`].
1157#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1158pub struct QueryUSOrdersResponse {
1159    /// Order list (raw JSON for forward compatibility).
1160    /// Order ID field is `id` (not `order_id`).
1161    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1162    pub orders: Vec<serde_json::Value>,
1163    /// Total number of orders matching the query.
1164    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1165    pub total_count: i32,
1166}
1167
1168/// One order state-transition entry within [`USOrderDetail`].
1169#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1170pub struct USOrderHistory {
1171    /// Execution type code
1172    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1173    pub exec_type: i32,
1174    /// Order status at this transition
1175    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1176    pub status: String,
1177    /// Price at this transition
1178    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1179    pub price: String,
1180    /// Quantity at this transition
1181    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1182    pub qty: String,
1183    /// Transition time (Unix-second string)
1184    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1185    pub time: String,
1186    /// Message / note
1187    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1188    pub msg: String,
1189    /// Whether the action was manual
1190    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1191    pub is_manually: bool,
1192    /// Counterparty ID
1193    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1194    pub opp_party_id: String,
1195    /// Trade match ID
1196    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1197    pub trd_match_id: String,
1198    /// Operator identifier
1199    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1200    pub operator: String,
1201    /// Entrust channel of the operation
1202    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1203    pub op_entrust_way: String,
1204    /// Cancel/reject response-to code
1205    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1206    pub cxl_rej_response_to: i32,
1207    /// Withdrawal reason
1208    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1209    pub withdrawal_reason: String,
1210    /// Counterparty name
1211    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1212    pub opp_name: String,
1213    /// Execution ID
1214    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1215    pub exec_id: String,
1216}
1217
1218/// Action-button state for an order.
1219#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1220pub struct USButtonControl {
1221    /// Whether the withdraw/cancel action is available
1222    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1223    pub withdraw: i32,
1224    /// Whether the replace/modify action is available
1225    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1226    pub replace: i32,
1227    /// Actions blocked with an exception reason
1228    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1229    pub exceptionable: Vec<String>,
1230}
1231
1232/// One fee category within [`USChargeDetail`].
1233#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1234pub struct USChargeItem {
1235    /// Fee category code
1236    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1237    pub code: i32,
1238    /// Fee category name
1239    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1240    pub name: String,
1241    /// Individual fee amounts in this category
1242    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1243    pub fees: Vec<String>,
1244}
1245
1246/// Fee breakdown for an order.
1247#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1248pub struct USChargeDetail {
1249    /// Fee currency
1250    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1251    pub currency: String,
1252    /// Total fee amount
1253    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1254    pub total_amount: String,
1255    /// Per-category fee breakdown
1256    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1257    pub items: Vec<USChargeItem>,
1258}
1259
1260/// One bracket/conditional sub-order attached to a main order.
1261#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1262pub struct USAttachedOrder {
1263    /// Attached-order type (display code)
1264    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1265    pub attached_type_display: i32,
1266    /// Executed quantity
1267    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1268    pub executed_qty: String,
1269    /// Order quantity
1270    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1271    pub quantity: String,
1272    /// Order status
1273    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1274    pub status: String,
1275    /// Trigger price
1276    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1277    pub trigger_price: String,
1278    /// Order ID
1279    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1280    pub order_id: String,
1281    /// Good-till date
1282    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1283    pub gtd: String,
1284    /// Time-in-force code
1285    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1286    pub time_in_force: i32,
1287    /// Order tag code
1288    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1289    pub tag: i32,
1290    /// Order type to activate on trigger
1291    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1292    pub activate_order_type: String,
1293    /// Whether to activate outside regular trading hours
1294    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1295    pub activate_rth: i32,
1296    /// Submitted price
1297    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1298    pub submit_price: String,
1299    /// User-facing trading symbol (e.g. `"NKE.US"`)
1300    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1301    pub symbol: String,
1302    /// Whether the order has been withdrawn
1303    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1304    pub withdrawn: bool,
1305}
1306
1307/// Full typed order object within [`USOrderDetailResponse`].
1308/// `submitted_at` and `done_at` are raw unix-second strings.
1309/// `order_histories` is nested inside this object, not at the response top
1310/// level.
1311#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1312pub struct USOrderDetail {
1313    /// Order ID
1314    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1315    pub id: String,
1316    /// Internal account ID
1317    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1318    pub aaid: String,
1319    /// Account channel
1320    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1321    pub account_channel: String,
1322    /// Order action code (buy/sell)
1323    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1324    pub action: i32,
1325    /// User-facing trading symbol (e.g. `"NKE.US"`)
1326    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1327    pub symbol: String,
1328    /// User-facing underlying symbol (options only)
1329    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1330    pub underlying_symbol: String,
1331    /// Security type
1332    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1333    pub security_type: String,
1334    /// Security name
1335    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1336    pub name: String,
1337    /// Order currency
1338    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1339    pub currency: String,
1340    /// Trade currency
1341    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1342    pub trade_currency: String,
1343    /// Order type
1344    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1345    pub order_type: String,
1346    /// Order status
1347    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1348    pub status: String,
1349    /// Order price
1350    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1351    pub price: String,
1352    /// Order quantity
1353    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1354    pub quantity: String,
1355    /// Executed quantity
1356    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1357    pub executed_qty: String,
1358    /// Executed price
1359    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1360    pub executed_price: String,
1361    /// Executed amount
1362    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1363    pub executed_amount: String,
1364    /// Operate direction
1365    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1366    pub operate_direction: String,
1367    /// Time-in-force code
1368    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1369    pub time_in_force: i32,
1370    /// Good-till date
1371    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1372    pub gtd: String,
1373    /// Order tag code
1374    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1375    pub tag: i32,
1376    /// Message / note
1377    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1378    pub msg: String,
1379    /// Whether the order is restricted to regular trading hours
1380    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1381    pub force_only_rth: i32,
1382    /// Submission time (Unix-second string)
1383    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1384    pub submitted_at: String,
1385    /// Completion time (Unix-second string)
1386    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1387    pub done_at: String,
1388    /// Trigger price
1389    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1390    pub trigger_price: String,
1391    /// Trigger time (Unix-second string)
1392    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1393    pub trigger_at: String,
1394    /// Trigger status code
1395    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1396    pub trigger_status: i32,
1397    /// Trigger exchange
1398    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1399    pub trigger_exchange: String,
1400    /// Last-done price at trigger
1401    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1402    pub trigger_last_done: String,
1403    /// Number of times triggered
1404    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1405    pub trigger_count: i32,
1406    /// Trailing amount (trailing-stop orders)
1407    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1408    pub tailing_amount: String,
1409    /// Trailing percent (trailing-stop orders)
1410    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1411    pub tailing_percent: String,
1412    /// Limit offset (trailing-limit orders)
1413    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1414    pub limit_offset: String,
1415    /// Order-book depth level for limit orders
1416    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1417    pub limit_depth_level: i32,
1418    /// Market price at reference
1419    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1420    pub market_price: String,
1421    /// Submitted amount
1422    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1423    pub submitted_amount: String,
1424    /// Estimated fee
1425    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1426    pub estimated_fee: String,
1427    /// Commission-free status code
1428    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1429    pub free_status: i32,
1430    /// Commission-free amount
1431    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1432    pub free_amount: String,
1433    /// Commission-free currency
1434    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1435    pub free_currency: String,
1436    /// Deduction status code
1437    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1438    pub deductions_status: i32,
1439    /// Deduction amount
1440    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1441    pub deductions_amount: String,
1442    /// Deduction currency
1443    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1444    pub deductions_currency: String,
1445    /// Platform deduction status code
1446    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1447    pub platform_deductions_status: i32,
1448    /// Platform deduction amount
1449    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1450    pub platform_deductions_amount: String,
1451    /// Platform deduction currency
1452    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1453    pub platform_deductions_currency: String,
1454    /// Display account
1455    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1456    pub display_account: String,
1457    /// Settlement account
1458    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1459    pub settlement_account: String,
1460    /// Settlement channel
1461    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1462    pub settlement_channel: String,
1463    /// Customer name
1464    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1465    pub customer_name: String,
1466    /// Account holder real name
1467    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1468    pub real_name: String,
1469    /// Account holder English name
1470    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1471    pub en_name: String,
1472    /// Joint-account holder real name
1473    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1474    pub joint_real_name: String,
1475    /// Joint-account holder English name
1476    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1477    pub joint_en_name: String,
1478    /// Organization ID
1479    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1480    pub org_id: String,
1481    /// Broker-to-client assigned number (HK)
1482    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1483    pub bcan: String,
1484    /// Entrust channel code
1485    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1486    pub op_entrust_way: i32,
1487    /// Entrust channel name
1488    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1489    pub op_entrust_way_name: String,
1490    /// Remark
1491    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1492    pub remark: String,
1493    /// Notice text
1494    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1495    pub notice: String,
1496    /// Short-sell type code
1497    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1498    pub short_sell_type: i32,
1499    /// Strategy (ploy) type
1500    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1501    pub ploy_type: String,
1502    /// Strategy (ploy) ID
1503    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1504    pub ploy_id: String,
1505    /// Strategy (ploy) status
1506    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1507    pub ploy_status: String,
1508    /// Trend direction code
1509    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1510    pub trend: i32,
1511    /// Withdrawal reason
1512    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1513    pub withdrawal_reason: String,
1514    /// Order type to activate on trigger
1515    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1516    pub activate_order_type: String,
1517    /// Whether to activate outside regular trading hours
1518    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1519    pub activate_rth: i32,
1520    /// Submitted price
1521    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1522    pub submit_price: String,
1523    /// Contract direction (options)
1524    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1525    pub contract_direction: String,
1526    /// Strike price (options)
1527    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1528    pub strike_price: String,
1529    /// Contract size (options)
1530    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1531    pub contract_size: String,
1532    /// Monitor price (conditional orders)
1533    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1534    pub monitor_price: String,
1535    /// Available action buttons
1536    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1537    pub button_control: USButtonControl,
1538    /// Fee breakdown (absent when not applicable)
1539    pub charge_detail: Option<USChargeDetail>,
1540    /// Attached bracket/conditional sub-orders
1541    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1542    pub attached_orders: Vec<USAttachedOrder>,
1543    /// Order state-transition history
1544    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1545    pub order_histories: Vec<USOrderHistory>,
1546}
1547
1548/// Response for [`crate::TradeContext::us_order_detail`].
1549/// Path: `GET /v1/us/orders/{order_id}`
1550#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1551pub struct USOrderDetailResponse {
1552    /// Full typed order object; None only on error.
1553    pub order: Option<USOrderDetail>,
1554    /// Active bracket/conditional sub-order, or None.
1555    pub current_attached_order: Option<USOrderDetail>,
1556    /// Server response timestamp (milliseconds string).
1557    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1558    pub current_millisecond: String,
1559}
1560
1561/// One cash currency entry in [`USAssetOverview`].
1562#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1563pub struct USCashEntry {
1564    /// Currency
1565    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1566    pub currency: String,
1567    /// Cash frozen for pending buys
1568    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1569    pub frozen_buy_cash: String,
1570    /// Outstanding (unsettled) amount
1571    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1572    pub outstanding: String,
1573    /// Settled cash
1574    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1575    pub settled_cash: String,
1576    /// Total amount
1577    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1578    pub total_amount: String,
1579    /// Total cash
1580    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1581    pub total_cash: String,
1582}
1583
1584/// One cryptocurrency holding in [`USAssetOverview`].
1585#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1586pub struct USCryptoEntry {
1587    /// Asset type (e.g. `"CRYPTO"`)
1588    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1589    pub asset_type: String,
1590    /// Trading-pair code (e.g. `"BTCUSD"`); the user-facing symbol is
1591    /// `"<symbol>.<market>"` (e.g. `"BTCUSD.BKKT"`)
1592    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1593    pub symbol: String,
1594    /// Holding quantity
1595    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1596    pub quantity: String,
1597    /// Settlement currency
1598    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1599    pub currency: String,
1600    /// Average cost price; empty when the server has none
1601    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1602    pub average_cost: String,
1603    /// Market code (e.g. `"BKKT"`)
1604    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1605    pub market: String,
1606    /// Trade status
1607    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1608    pub trade_status: String,
1609    /// Previous close price
1610    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1611    pub prev_close: String,
1612    /// Latest price
1613    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1614    pub last_done: String,
1615    /// Market price
1616    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1617    pub market_price: String,
1618    /// Pre-market close price
1619    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1620    pub pretrade_close: String,
1621    /// Today's investment value
1622    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1623    pub stock_invest_of_today: String,
1624    /// Today's profit/loss
1625    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1626    pub today_pl: String,
1627    /// Today's investment value (pre-market)
1628    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1629    pub pretrade_stock_invest_of_today: String,
1630    /// Today's profit/loss (pre-market)
1631    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1632    pub pretrade_today_pl: String,
1633    /// Overnight-session latest price
1634    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1635    pub night_last_done: String,
1636    /// Overnight-session previous close
1637    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1638    pub night_prev_close: String,
1639    /// Position side (long/short)
1640    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1641    pub position_side: String,
1642    /// Position open time (Unix-second string; `"0"` when unknown)
1643    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1644    pub open_position_time: String,
1645    /// Asset name (e.g. `"Bitcoin"`)
1646    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1647    pub name: String,
1648    /// Industry classification ID
1649    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1650    pub industry_counter_id: String,
1651    /// Industry name
1652    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1653    pub industry_name: String,
1654}
1655
1656/// One stock/equity position in [`USAssetOverview`].
1657#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1658pub struct USStockEntry {
1659    /// Ticker code returned by the API (e.g. `"AAPL"`). See `full_symbol` for
1660    /// the qualified form.
1661    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1662    pub symbol: String,
1663    /// Qualified user-facing symbol (e.g. `"AAPL.US"`)
1664    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1665    pub full_symbol: String,
1666    /// Asset type
1667    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1668    pub asset_type: String,
1669    /// Holding quantity
1670    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1671    pub quantity: String,
1672    /// Currency
1673    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1674    pub currency: String,
1675    /// Average cost price
1676    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1677    pub average_cost: String,
1678    /// Market code
1679    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1680    pub market: String,
1681    /// Trade status
1682    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1683    pub trade_status: String,
1684    /// Previous close price
1685    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1686    pub prev_close: String,
1687    /// Latest price
1688    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1689    pub last_done: String,
1690    /// Market price
1691    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1692    pub market_price: String,
1693    /// Pre-market close price
1694    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1695    pub pretrade_close: String,
1696    /// Today's stock investment value
1697    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1698    pub stock_invest_of_today: String,
1699    /// Today's profit/loss
1700    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1701    pub today_pl: String,
1702    /// Today's stock investment value (pre-market)
1703    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1704    pub pretrade_stock_invest_of_today: String,
1705    /// Today's profit/loss (pre-market)
1706    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1707    pub pretrade_today_pl: String,
1708    /// Overnight-session latest price
1709    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1710    pub night_last_done: String,
1711    /// Overnight-session previous close
1712    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1713    pub night_prev_close: String,
1714    /// Position side (long/short)
1715    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1716    pub position_side: String,
1717    /// Position open time (Unix-second string)
1718    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1719    pub open_position_time: String,
1720    /// Security name
1721    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1722    pub name: String,
1723    /// Industry classification ID
1724    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1725    pub industry_counter_id: String,
1726    /// Industry name
1727    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1728    pub industry_name: String,
1729}
1730
1731/// Response for [`crate::TradeContext::us_asset_overview`].
1732/// Field names match the actual API response from `GET /v1/us/assets/overview`.
1733#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1734pub struct USAssetOverview {
1735    /// Account type
1736    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1737    pub account_type: String,
1738    /// Account snapshot timestamp (Unix-second string → OffsetDateTime).
1739    #[serde(default, with = "crate::serde_utils::timestamp_opt")]
1740    pub asset_timestamp: Option<time::OffsetDateTime>,
1741    /// Cash buying power (top-level convenience field).
1742    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1743    pub cash_buy_power: String,
1744    /// Overnight buying power
1745    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1746    pub overnight_buy_power: String,
1747    /// Account currency
1748    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1749    pub currency: String,
1750    /// Cash balances per currency
1751    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1752    pub cash_list: Vec<USCashEntry>,
1753    /// Stock/equity positions
1754    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1755    pub stock_list: Vec<USStockEntry>,
1756    /// Option positions (raw JSON)
1757    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1758    pub option_list: Vec<serde_json::Value>,
1759    /// Cryptocurrency holdings
1760    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1761    pub crypto_list: Vec<USCryptoEntry>,
1762    /// Multi-leg option strategies (raw JSON)
1763    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1764    pub multi_leg: serde_json::Value,
1765}
1766
1767/// One time-period metric in a [`USRealizedPLEntry`].
1768#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1769pub struct USRealizedPLMetric {
1770    /// Realized P&L amount
1771    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1772    pub amount: String,
1773    /// Period code (server-defined; 2 = current month observed in testing).
1774    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1775    pub period: i32,
1776    /// Realized P&L rate
1777    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1778    pub rate: String,
1779}
1780
1781/// One asset-category entry in [`USRealizedPL`].
1782/// `category`: 0 = all, 1 = stock, 2 = option, 3 = crypto (server-defined).
1783#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1784pub struct USRealizedPLEntry {
1785    /// Asset category (0 = all, 1 = stock, 2 = option, 3 = crypto)
1786    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1787    pub category: i32,
1788    /// Currency
1789    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1790    pub currency: String,
1791    /// Per-period realized P&L metrics
1792    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1793    pub metrics: Vec<USRealizedPLMetric>,
1794}
1795
1796/// Request for [`crate::TradeContext::us_realized_pl`], modelled after
1797/// [`crate::GetUSHistoryOrders`].
1798#[derive(Debug, Clone, Default)]
1799pub struct GetUSRealizedPLOptions {
1800    /// Currency, e.g. `"USD"`. Defaults to `"USD"` if empty.
1801    pub currency: String,
1802    /// Asset category filter: `""` = all, `"STOCK"`, `"OPTION"`, `"CRYPTO"`.
1803    pub category: String,
1804}
1805
1806/// Response for [`crate::TradeContext::us_realized_pl`].
1807/// Field name matches the actual API response from `GET
1808/// /v1/us/assets/pl/realized`.
1809#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1810pub struct USRealizedPL {
1811    /// Per-asset-category realized P&L entries
1812    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1813    pub realized_pl_list: Vec<USRealizedPLEntry>,
1814}
1815
1816/// Request for [`crate::TradeContext::us_available_holding`].
1817#[derive(Debug, Clone, Default)]
1818pub struct GetUSAvailableHoldingOptions {
1819    /// Security symbol, e.g. `"AAPL.US"`, an option symbol such as
1820    /// `"AAPL261120C345000.US"`, or a crypto pair such as `"BTCUSD.BKKT"`.
1821    pub symbol: String,
1822    /// Holding type: `"STOCK"`, `"OPTION"` or `"CRYPTO"`. Defaults to
1823    /// `"STOCK"` if empty.
1824    pub equity_type: String,
1825    /// Position side: `"LONG"` or `"SHORT"`. Defaults to `"LONG"` if empty.
1826    pub position_side: String,
1827}
1828
1829/// Response for [`crate::TradeContext::us_available_holding`].
1830#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1831pub struct USAvailableHolding {
1832    /// Quantity available to sell (long) or buy to cover (short); negative for
1833    /// a short position
1834    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1835    pub available_qty: String,
1836}
1837
1838/// Buying power in [`USCashAndBuyPower`].
1839#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1840pub struct USBuyLimitInfo {
1841    /// Currency
1842    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1843    pub currency: String,
1844    /// Cash buying power
1845    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1846    pub cash_buy_power: String,
1847    /// Overnight buying power
1848    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1849    pub overnight_buy_power: String,
1850    /// Day-trade buying power
1851    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1852    pub day_trade_buy_power: String,
1853    /// Instant buying power
1854    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1855    pub instant_buy_power: String,
1856    /// Intraday margin buying power
1857    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1858    pub intraday_margin_buy_power: String,
1859    /// Option buying power
1860    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1861    pub option_buy_power: String,
1862    /// Crypto buying power
1863    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1864    pub crypto_buy_power: String,
1865    /// Margin maintenance excess used for buying power
1866    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1867    pub mme: String,
1868}
1869
1870/// One cash currency entry in [`USCashAndBuyPower`].
1871#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1872pub struct USCashDetail {
1873    /// Currency
1874    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1875    pub currency: String,
1876    /// Total cash
1877    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1878    pub total_amount: String,
1879    /// Available cash
1880    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1881    pub available_cash: String,
1882    /// Withdrawable cash
1883    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1884    pub withdraw_cash: String,
1885    /// Cash frozen for pending orders
1886    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1887    pub frozen_cash: String,
1888    /// Settled cash
1889    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1890    pub settled_cash: String,
1891    /// Outstanding (unsettled) amount
1892    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1893    pub outstanding: String,
1894    /// Amount held for external use (e.g. IPO or fund subscriptions)
1895    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1896    pub external_amount: String,
1897}
1898
1899/// Margin account status in [`USCashAndBuyPower`].
1900#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1901pub struct USMarginStatus {
1902    /// Currency
1903    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1904    pub currency: String,
1905    /// Net liquidation value
1906    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1907    pub nlv: String,
1908    /// Margin equity
1909    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1910    pub margin_equity: String,
1911    /// Margin maintenance excess
1912    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1913    pub margin_maintenance_excess: String,
1914    /// Maintenance margin requirement
1915    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1916    pub mmr: String,
1917    /// Regulation T excess
1918    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1919    pub reg_t_excess: String,
1920    /// Special memorandum account
1921    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1922    pub sma: String,
1923}
1924
1925/// Response for [`crate::TradeContext::us_cash_and_buy_power`].
1926/// Field names match `GET /v1/us/assets/cash-and-buy-power`.
1927#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1928pub struct USCashAndBuyPower {
1929    /// Buying power
1930    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1931    pub buy_limit_info: USBuyLimitInfo,
1932    /// Cash per currency
1933    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1934    pub cash_list: Vec<USCashDetail>,
1935    /// Margin account status
1936    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1937    pub margin_status: USMarginStatus,
1938}
1939
1940/// Request for [`crate::TradeContext::us_transaction_history`].
1941#[derive(Debug, Clone)]
1942pub struct GetUSTransactionHistoryOptions {
1943    /// Start time (inclusive)
1944    pub start_at: OffsetDateTime,
1945    /// End time (inclusive)
1946    pub end_at: OffsetDateTime,
1947    /// Page number, starting at 1. Defaults to 1 if 0.
1948    pub page: i32,
1949    /// Page size. Defaults to 20 if 0.
1950    pub size: i32,
1951    /// Transaction types to include; empty means all. Values:
1952    /// `"TT_DEPOSIT_AND_WITHDRAWAL"`, `"TT_STOCKS_AND_ETFS_TRADING"`,
1953    /// `"TT_OPTIONS_TRADING"`, `"TT_CRYPTO_TRADING"`, `"TT_CORPORATE_ACTION"`,
1954    /// `"TT_TRANSFER_IN_AND_OUT"`, `"TT_CRYPTO_TRANSFER"`,
1955    /// `"TT_MARGIN_FINANCING"`, `"TT_OTHER"`.
1956    pub types: Vec<String>,
1957    /// Currency filter, e.g. `"USD"`; empty means all.
1958    pub currency: String,
1959}
1960
1961impl GetUSTransactionHistoryOptions {
1962    /// Create a request for transactions between `start_at` and `end_at`.
1963    pub fn new(start_at: OffsetDateTime, end_at: OffsetDateTime) -> Self {
1964        Self {
1965            start_at,
1966            end_at,
1967            page: 1,
1968            size: 20,
1969            types: Vec::new(),
1970            currency: String::new(),
1971        }
1972    }
1973}
1974
1975/// One record in [`USTransactionHistory`].
1976#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1977pub struct USTransaction {
1978    /// Display title
1979    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1980    pub title: String,
1981    /// Business code
1982    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1983    pub biz_code: String,
1984    /// Business code name
1985    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1986    pub biz_code_name: String,
1987    /// Amount; negative for outflows
1988    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1989    pub amount: String,
1990    /// Currency
1991    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1992    pub currency: String,
1993    /// Security symbol, if the record relates to one (e.g. `"AAPL.US"`)
1994    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1995    pub symbol: String,
1996    /// Market code
1997    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1998    pub market: String,
1999    /// Holding type
2000    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2001    pub equity_type: String,
2002    /// Position side
2003    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2004    pub position_side: String,
2005    /// Quantity
2006    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2007    pub quantity: String,
2008    /// Quantity description
2009    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2010    pub quantity_description: String,
2011    /// Reference number
2012    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2013    pub ref_no: String,
2014    /// Remark
2015    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2016    pub remark: String,
2017    /// Creation time
2018    #[serde(
2019        default,
2020        deserialize_with = "crate::serde_utils::timestamp_opt_lenient::deserialize",
2021        serialize_with = "crate::serde_utils::rfc3339_opt::serialize"
2022    )]
2023    pub create_at: Option<OffsetDateTime>,
2024    /// Completion time
2025    #[serde(
2026        default,
2027        deserialize_with = "crate::serde_utils::timestamp_opt_lenient::deserialize",
2028        serialize_with = "crate::serde_utils::rfc3339_opt::serialize"
2029    )]
2030    pub done_at: Option<OffsetDateTime>,
2031}
2032
2033/// Response for [`crate::TradeContext::us_transaction_history`].
2034/// Field names match `POST /v1/us/assets/transaction-history`.
2035#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2036pub struct USTransactionHistory {
2037    /// Current page number
2038    #[serde(default, with = "crate::serde_utils::int64_str")]
2039    pub current_page: i64,
2040    /// Records on this page. The API returns no total count: a page shorter
2041    /// than the requested size is the last one.
2042    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2043    pub items: Vec<USTransaction>,
2044}
2045
2046/// One exchange rate in [`USExchangeRates`].
2047#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2048pub struct USExchangeRate {
2049    /// Account channel the rates apply to, e.g. `"us_lb_apex"` (outer
2050    /// `universal_exchanges` key)
2051    pub universal_key: String,
2052    /// Rate type, e.g. `"am"` or `"reference"` (inner `spec_exchanges` key)
2053    pub spec_key: String,
2054    /// Base currency
2055    pub base_currency: String,
2056    /// Other (quote) currency
2057    pub other_currency: String,
2058    /// Bid rate
2059    pub bid_rate: String,
2060    /// Offer rate
2061    pub offer_rate: String,
2062    /// Average rate
2063    pub average_rate: String,
2064}
2065
2066/// Response for [`crate::TradeContext::us_exchange_rates`].
2067///
2068/// The upstream response is a two-level map
2069/// (`universal_exchanges.<key>.spec_exchanges.<key>.exchanges[]`); it is
2070/// flattened into a single list, sorted by the two upstream map keys, with
2071/// the keys kept on each entry as [`USExchangeRate::universal_key`] and
2072/// [`USExchangeRate::spec_key`].
2073#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2074#[serde(from = "RawUSExchangeRates")]
2075pub struct USExchangeRates {
2076    /// Exchange rates
2077    pub exchanges: Vec<USExchangeRate>,
2078}
2079
2080#[derive(Deserialize, Default)]
2081struct RawUSExchangeRate {
2082    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2083    base_currency: String,
2084    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2085    other_currency: String,
2086    #[serde(default, with = "crate::serde_utils::value_as_opt_string")]
2087    bid_rate: Option<String>,
2088    #[serde(default, with = "crate::serde_utils::value_as_opt_string")]
2089    offer_rate: Option<String>,
2090    #[serde(default, with = "crate::serde_utils::value_as_opt_string")]
2091    average_rate: Option<String>,
2092}
2093
2094#[derive(Deserialize, Default)]
2095struct RawUSSpecExchanges {
2096    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2097    exchanges: Vec<RawUSExchangeRate>,
2098}
2099
2100#[derive(Deserialize, Default)]
2101struct RawUSUniversalExchanges {
2102    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2103    spec_exchanges: BTreeMap<String, RawUSSpecExchanges>,
2104}
2105
2106#[derive(Deserialize, Default)]
2107struct RawUSExchangeRates {
2108    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2109    universal_exchanges: BTreeMap<String, RawUSUniversalExchanges>,
2110    /// Already-flattened form, so that the serialized [`USExchangeRates`]
2111    /// deserializes back.
2112    #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
2113    exchanges: Vec<USExchangeRate>,
2114}
2115
2116impl From<RawUSExchangeRates> for USExchangeRates {
2117    fn from(raw: RawUSExchangeRates) -> Self {
2118        let mut exchanges = raw.exchanges;
2119        for (universal_key, universal) in raw.universal_exchanges {
2120            for (spec_key, spec) in universal.spec_exchanges {
2121                exchanges.extend(spec.exchanges.into_iter().map(|rate| USExchangeRate {
2122                    universal_key: universal_key.clone(),
2123                    spec_key: spec_key.clone(),
2124                    base_currency: rate.base_currency,
2125                    other_currency: rate.other_currency,
2126                    bid_rate: rate.bid_rate.unwrap_or_default(),
2127                    offer_rate: rate.offer_rate.unwrap_or_default(),
2128                    average_rate: rate.average_rate.unwrap_or_default(),
2129                }));
2130            }
2131        }
2132        Self { exchanges }
2133    }
2134}
2135
2136#[cfg(test)]
2137mod tests {
2138    use time::macros::datetime;
2139
2140    use super::*;
2141
2142    #[test]
2143    fn execution_without_side_defaults_to_unknown() {
2144        // `/v1/trade/execution/history` on a LongPort US account returns
2145        // trades with no `side`; they must still deserialize.
2146        let data = r#"{
2147            "order_id": "1000000000000000001",
2148            "trade_id": "1000000000000000001-1",
2149            "symbol": "ETHUSD.BKKT",
2150            "trade_done_at": "1790203596",
2151            "quantity": "0.168",
2152            "price": "2690.34165646"
2153        }"#;
2154        let execution: Execution = serde_json::from_str(data).expect("execution without side");
2155        assert_eq!(
2156            execution.side,
2157            OrderSide::Unknown,
2158            "missing side defaults to Unknown"
2159        );
2160        assert_eq!(execution.symbol, "ETHUSD.BKKT", "symbol is kept");
2161    }
2162
2163    #[test]
2164    fn us_exchange_rates_response() {
2165        let data = r#"{
2166            "universal_exchanges": {
2167                "2": {"spec_exchanges": {"USD": {"exchanges": [
2168                    {"base_currency": "USD", "other_currency": "HKD", "bid_rate": 7.8, "offer_rate": "7.85", "average_rate": null}
2169                ]}}},
2170                "1": {"spec_exchanges": {
2171                    "b": {"exchanges": [{"base_currency": "USD", "other_currency": "CNH", "bid_rate": "7.1"}]},
2172                    "a": {"exchanges": null}
2173                }}
2174            }
2175        }"#;
2176        let resp: USExchangeRates = serde_json::from_str(data).unwrap();
2177        assert_eq!(resp.exchanges.len(), 2);
2178        assert_eq!(resp.exchanges[0].universal_key, "1");
2179        assert_eq!(resp.exchanges[0].spec_key, "b");
2180        assert_eq!(resp.exchanges[0].other_currency, "CNH");
2181        assert_eq!(resp.exchanges[0].offer_rate, "");
2182        assert_eq!(resp.exchanges[1].universal_key, "2");
2183        assert_eq!(resp.exchanges[1].spec_key, "USD");
2184        assert_eq!(resp.exchanges[1].bid_rate, "7.8");
2185        assert_eq!(resp.exchanges[1].offer_rate, "7.85");
2186        assert_eq!(resp.exchanges[1].average_rate, "");
2187
2188        let json = serde_json::to_string(&resp).unwrap();
2189        let back: USExchangeRates = serde_json::from_str(&json).unwrap();
2190        assert_eq!(back.exchanges.len(), 2);
2191        assert_eq!(back.exchanges[1].bid_rate, "7.8");
2192    }
2193
2194    #[test]
2195    fn us_cash_and_buy_power_response() {
2196        let data = r#"{
2197            "buy_limit_info": {"currency": "USD", "cash_buy_power": "100.5", "overnight_buy_power": "90"},
2198            "cash_list": [{"currency": "USD", "total_amount": "120", "available_cash": "100.5", "withdraw_cash": "80", "frozen_cash": null}],
2199            "margin_status": {"currency": "USD", "nlv": "1200"}
2200        }"#;
2201        let resp: USCashAndBuyPower = serde_json::from_str(data).unwrap();
2202        assert_eq!(resp.buy_limit_info.cash_buy_power, "100.5");
2203        assert_eq!(resp.cash_list[0].withdraw_cash, "80");
2204        assert_eq!(resp.cash_list[0].frozen_cash, "");
2205        assert_eq!(resp.margin_status.nlv, "1200");
2206    }
2207
2208    #[test]
2209    fn us_transaction_history_response() {
2210        let data = r#"{
2211            "current_page": "2",
2212            "items": [
2213                {"title": "Buy", "amount": "-100", "currency": "USD", "symbol": "AAPL.US", "create_at": "1792600000", "done_at": 1792600060},
2214                {"title": "Buy", "amount": "-10", "currency": "USD", "symbol": "BTCUSD.BKKT", "counter_id": "VA/BKKT/BTCUSD", "done_at": "0"}
2215            ]
2216        }"#;
2217        let resp: USTransactionHistory = serde_json::from_str(data).unwrap();
2218        assert_eq!(resp.current_page, 2);
2219        assert_eq!(resp.items[0].symbol, "AAPL.US");
2220        assert_eq!(
2221            resp.items[0].create_at.unwrap().unix_timestamp(),
2222            1792600000
2223        );
2224        assert_eq!(resp.items[0].done_at.unwrap().unix_timestamp(), 1792600060);
2225        assert_eq!(resp.items[1].symbol, "BTCUSD.BKKT");
2226        assert!(resp.items[1].done_at.is_none());
2227    }
2228
2229    /// Shapes (field names, JSON types, map keys) as returned by US prod.
2230    #[test]
2231    fn us_asset_responses_as_returned_by_prod() {
2232        let data = r#"{
2233            "current_page": 1,
2234            "items": [{
2235                "amount": "0.5", "biz_code": "LVAVNSCR", "biz_code_name": "Cryptocurrency Deposit",
2236                "counter_id": "VA/BKKT/BTCUSD", "create_at": "1791478565", "currency": "",
2237                "done_at": "1791478565", "equity_type": "CRYPTO", "market": "BKKT",
2238                "position_side": "LONG", "quantity": "0.5", "quantity_description": "0.5",
2239                "ref_no": "R1", "remark": "", "symbol": "BTCUSD.BKKT",
2240                "title": "Cryptocurrency Deposit: BTCUSD"
2241            }]
2242        }"#;
2243        let resp: USTransactionHistory = serde_json::from_str(data).unwrap();
2244        assert_eq!(resp.current_page, 1);
2245        assert_eq!(resp.items[0].symbol, "BTCUSD.BKKT");
2246        assert_eq!(resp.items[0].equity_type, "CRYPTO");
2247        assert_eq!(resp.items[0].done_at.unwrap().unix_timestamp(), 1791478565);
2248
2249        let data = r#"{"universal_exchanges": {"us_lb_apex": {"spec_exchanges": {
2250            "reference": {"exchanges": [{"average_rate": 1, "base_currency": "USD", "bid_rate": 1, "offer_rate": 1, "other_currency": "USD"}]},
2251            "am": {"exchanges": [{"average_rate": 1, "base_currency": "USD", "bid_rate": 1, "offer_rate": 1, "other_currency": "USD"}]}
2252        }}}}"#;
2253        let resp: USExchangeRates = serde_json::from_str(data).unwrap();
2254        let keys: Vec<_> = resp
2255            .exchanges
2256            .iter()
2257            .map(|e| (e.universal_key.as_str(), e.spec_key.as_str()))
2258            .collect();
2259        assert_eq!(keys, [("us_lb_apex", "am"), ("us_lb_apex", "reference")]);
2260        assert_eq!(resp.exchanges[0].average_rate, "1");
2261
2262        let data = r#"{
2263            "account_type": "1", "asset_timestamp": "1792661597", "currency": "USD",
2264            "stock_list": [{"symbol": "MULL", "full_symbol": "MULL.US", "counter_id": "ETF/US/MULL", "quantity": "10", "market": "US"}],
2265            "crypto_list": [{
2266                "asset_type": "CRYPTO", "average_cost": "", "counter_id": "VA/BKKT/ETHUSD",
2267                "currency": "USD", "last_done": "2500", "market": "BKKT", "market_price": "2500",
2268                "name": "Ethereum", "open_position_time": "0", "position_side": "LONG",
2269                "quantity": "0.1", "symbol": "ETHUSD", "today_pl": "", "trade_status": "105"
2270            }],
2271            "option_list": [], "multi_leg": {"holdings": []}
2272        }"#;
2273        let resp: USAssetOverview = serde_json::from_str(data).unwrap();
2274        assert_eq!(resp.asset_timestamp.unwrap().unix_timestamp(), 1792661597);
2275        assert_eq!(resp.stock_list[0].full_symbol, "MULL.US");
2276        let crypto = &resp.crypto_list[0];
2277        assert_eq!(crypto.symbol, "ETHUSD");
2278        assert_eq!(crypto.market, "BKKT");
2279        assert_eq!(crypto.quantity, "0.1");
2280        assert_eq!(crypto.name, "Ethereum");
2281        assert_eq!(crypto.market_price, "2500");
2282    }
2283
2284    #[test]
2285    fn fund_position_response() {
2286        let data = r#"
2287        {
2288            "list": [{
2289                "account_channel": "lb",
2290                "fund_info": [{
2291                    "counter_id": "UT/FD/HK0000447943",
2292                    "symbol_name": "高腾亚洲收益基金",
2293                    "currency": "USD",
2294                    "holding_units": "5.000",
2295                    "current_net_asset_value": "0",
2296                    "cost_net_asset_value": "0.00",
2297                    "net_asset_value_day": "1649865600"
2298                }]
2299            }]
2300        }
2301        "#;
2302
2303        let resp: FundPositionsResponse = serde_json::from_str(data).unwrap();
2304        assert_eq!(resp.channels.len(), 1);
2305
2306        let channel = &resp.channels[0];
2307        assert_eq!(channel.account_channel, "lb");
2308        assert_eq!(channel.positions.len(), 1);
2309
2310        let position = &channel.positions[0];
2311        assert_eq!(position.counter_id, "UT/FD/HK0000447943");
2312        assert_eq!(position.symbol_name, "高腾亚洲收益基金");
2313        assert_eq!(position.currency, "USD");
2314        assert_eq!(position.current_net_asset_value, decimal!(0i32));
2315        assert_eq!(position.cost_net_asset_value, decimal!(0i32));
2316        assert_eq!(position.holding_units, decimal!(5i32));
2317        assert_eq!(position.net_asset_value_day, datetime!(2022-4-14 0:00 +8));
2318
2319        // Transition compatibility: the legacy `symbol` key (which carried a
2320        // bare ISIN) still deserializes into `counter_id` via the serde alias.
2321        let legacy = r#"{"list":[{"account_channel":"lb","fund_info":[{"symbol":"HK0000447943","symbol_name":"x","currency":"USD","holding_units":"0","current_net_asset_value":"0","cost_net_asset_value":"0","net_asset_value_day":"1649865600"}]}]}"#;
2322        let resp: FundPositionsResponse = serde_json::from_str(legacy).unwrap();
2323        assert_eq!(resp.channels[0].positions[0].counter_id, "HK0000447943");
2324    }
2325
2326    #[test]
2327    fn stock_position_response() {
2328        let data = r#"
2329        {
2330            "list": [
2331              {
2332                "account_channel": "lb",
2333                "stock_info": [
2334                  {
2335                    "symbol": "700.HK",
2336                    "symbol_name": "腾讯控股",
2337                    "currency": "HK",
2338                    "quantity": "650",
2339                    "available_quantity": "-450",
2340                    "cost_price": "457.53",
2341                    "market": "HK",
2342                    "init_quantity": "2000"
2343                  },
2344                  {
2345                    "symbol": "9991.HK",
2346                    "symbol_name": "宝尊电商-SW",
2347                    "currency": "HK",
2348                    "quantity": "200",
2349                    "available_quantity": "0",
2350                    "cost_price": "32.25",
2351                    "market": "HK",
2352                    "init_quantity": ""
2353                  }
2354                ]
2355              }
2356            ]
2357          }
2358        "#;
2359
2360        let resp: StockPositionsResponse = serde_json::from_str(data).unwrap();
2361        assert_eq!(resp.channels.len(), 1);
2362
2363        let channel = &resp.channels[0];
2364        assert_eq!(channel.account_channel, "lb");
2365        assert_eq!(channel.positions.len(), 2);
2366
2367        let position = &channel.positions[0];
2368        assert_eq!(position.symbol, "700.HK");
2369        assert_eq!(position.symbol_name, "腾讯控股");
2370        assert_eq!(position.currency, "HK");
2371        assert_eq!(position.quantity, decimal!(650));
2372        assert_eq!(position.available_quantity, decimal!(-450));
2373        assert_eq!(position.cost_price, decimal!(457.53f32));
2374        assert_eq!(position.market, Market::HK);
2375        assert_eq!(position.init_quantity, Some(decimal!(2000)));
2376
2377        let position = &channel.positions[0];
2378        assert_eq!(position.symbol, "700.HK");
2379        assert_eq!(position.symbol_name, "腾讯控股");
2380        assert_eq!(position.currency, "HK");
2381        assert_eq!(position.quantity, decimal!(650));
2382        assert_eq!(position.available_quantity, decimal!(-450));
2383        assert_eq!(position.cost_price, decimal!(457.53f32));
2384        assert_eq!(position.market, Market::HK);
2385
2386        let position = &channel.positions[1];
2387        assert_eq!(position.symbol, "9991.HK");
2388        assert_eq!(position.symbol_name, "宝尊电商-SW");
2389        assert_eq!(position.currency, "HK");
2390        assert_eq!(position.quantity, decimal!(200));
2391        assert_eq!(position.available_quantity, decimal!(0));
2392        assert_eq!(position.cost_price, decimal!(32.25f32));
2393        assert_eq!(position.init_quantity, None);
2394    }
2395
2396    #[test]
2397    fn cash_flow() {
2398        let data = r#"
2399        {
2400            "list": [
2401              {
2402                "transaction_flow_name": "BuyContract-Stocks",
2403                "direction": 1,
2404                "balance": "-248.60",
2405                "currency": "USD",
2406                "business_type": 1,
2407                "business_time": "1621507957",
2408                "symbol": "AAPL.US",
2409                "description": "AAPL"
2410              },
2411              {
2412                "transaction_flow_name": "BuyContract-Stocks",
2413                "direction": 1,
2414                "balance": "-125.16",
2415                "currency": "USD",
2416                "business_type": 2,
2417                "business_time": "1621504824",
2418                "symbol": "AAPL.US",
2419                "description": "AAPL"
2420              }
2421            ]
2422          }
2423          "#;
2424
2425        #[derive(Debug, Deserialize)]
2426        struct Response {
2427            list: Vec<CashFlow>,
2428        }
2429
2430        let resp: Response = serde_json::from_str(data).unwrap();
2431        assert_eq!(resp.list.len(), 2);
2432
2433        let cashflow = &resp.list[0];
2434        assert_eq!(cashflow.transaction_flow_name, "BuyContract-Stocks");
2435        assert_eq!(cashflow.direction, CashFlowDirection::Out);
2436        assert_eq!(cashflow.balance, decimal!(-248.60f32));
2437        assert_eq!(cashflow.currency, "USD");
2438        assert_eq!(cashflow.business_type, BalanceType::Cash);
2439        assert_eq!(cashflow.business_time, datetime!(2021-05-20 18:52:37 +8));
2440        assert_eq!(cashflow.symbol.as_deref(), Some("AAPL.US"));
2441        assert_eq!(cashflow.description, "AAPL");
2442
2443        let cashflow = &resp.list[1];
2444        assert_eq!(cashflow.transaction_flow_name, "BuyContract-Stocks");
2445        assert_eq!(cashflow.direction, CashFlowDirection::Out);
2446        assert_eq!(cashflow.balance, decimal!(-125.16f32));
2447        assert_eq!(cashflow.currency, "USD");
2448        assert_eq!(cashflow.business_type, BalanceType::Stock);
2449        assert_eq!(cashflow.business_time, datetime!(2021-05-20 18:00:24 +8));
2450        assert_eq!(cashflow.symbol.as_deref(), Some("AAPL.US"));
2451        assert_eq!(cashflow.description, "AAPL");
2452    }
2453
2454    #[test]
2455    fn account_balance() {
2456        let data = r#"
2457        {
2458            "list": [
2459              {
2460                "total_cash": "1759070010.72",
2461                "max_finance_amount": "977582000",
2462                "remaining_finance_amount": "0",
2463                "risk_level": "1",
2464                "margin_call": "2598051051.50",
2465                "currency": "HKD",
2466                "cash_infos": [
2467                  {
2468                    "withdraw_cash": "97592.30",
2469                    "available_cash": "195902464.37",
2470                    "frozen_cash": "11579339.13",
2471                    "settling_cash": "207288537.81",
2472                    "currency": "HKD"
2473                  },
2474                  {
2475                    "withdraw_cash": "199893416.74",
2476                    "available_cash": "199893416.74",
2477                    "frozen_cash": "28723.76",
2478                    "settling_cash": "-276806.51",
2479                    "currency": "USD"
2480                  }
2481                ],
2482                "net_assets": "11111.12",
2483                "init_margin": "2222.23",
2484                "maintenance_margin": "3333.45",
2485                "buy_power": "1234.67",
2486                "frozen_transaction_fees": [
2487                    {
2488                        "currency": "HKD",
2489                        "frozen_transaction_fee": "123"
2490                    }
2491                ]
2492              }
2493            ]
2494          }"#;
2495
2496        #[derive(Debug, Deserialize)]
2497        struct Response {
2498            list: Vec<AccountBalance>,
2499        }
2500
2501        let resp: Response = serde_json::from_str(data).unwrap();
2502        assert_eq!(resp.list.len(), 1);
2503
2504        let balance = &resp.list[0];
2505        assert_eq!(balance.total_cash, "1759070010.72".parse().unwrap());
2506        assert_eq!(balance.max_finance_amount, "977582000".parse().unwrap());
2507        assert_eq!(balance.remaining_finance_amount, decimal!(0i32));
2508        assert_eq!(balance.risk_level, 1);
2509        assert_eq!(balance.margin_call, "2598051051.50".parse().unwrap());
2510        assert_eq!(balance.currency, "HKD");
2511        assert_eq!(balance.net_assets, "11111.12".parse().unwrap());
2512        assert_eq!(balance.init_margin, "2222.23".parse().unwrap());
2513        assert_eq!(balance.maintenance_margin, "3333.45".parse().unwrap());
2514        assert_eq!(balance.buy_power, "1234.67".parse().unwrap());
2515
2516        assert_eq!(balance.cash_infos.len(), 2);
2517
2518        let cash_info = &balance.cash_infos[0];
2519        assert_eq!(cash_info.withdraw_cash, "97592.30".parse().unwrap());
2520        assert_eq!(cash_info.available_cash, "195902464.37".parse().unwrap());
2521        assert_eq!(cash_info.frozen_cash, "11579339.13".parse().unwrap());
2522        assert_eq!(cash_info.settling_cash, "207288537.81".parse().unwrap());
2523        assert_eq!(cash_info.currency, "HKD");
2524
2525        let cash_info = &balance.cash_infos[1];
2526        assert_eq!(cash_info.withdraw_cash, "199893416.74".parse().unwrap());
2527        assert_eq!(cash_info.available_cash, "199893416.74".parse().unwrap());
2528        assert_eq!(cash_info.frozen_cash, "28723.76".parse().unwrap());
2529        assert_eq!(cash_info.settling_cash, "-276806.51".parse().unwrap());
2530        assert_eq!(cash_info.currency, "USD");
2531
2532        assert_eq!(balance.frozen_transaction_fees.len(), 1);
2533
2534        let frozen_transaction_fee = &balance.frozen_transaction_fees[0];
2535        assert_eq!(frozen_transaction_fee.currency, "HKD");
2536        assert_eq!(
2537            frozen_transaction_fee.frozen_transaction_fee,
2538            "123".parse().unwrap()
2539        );
2540    }
2541
2542    #[test]
2543    fn history_orders() {
2544        let data = r#"
2545        {
2546            "orders": [
2547              {
2548                "currency": "HKD",
2549                "executed_price": "0.000",
2550                "executed_quantity": "0",
2551                "expire_date": "",
2552                "last_done": "",
2553                "limit_offset": "",
2554                "msg": "",
2555                "order_id": "706388312699592704",
2556                "order_type": "ELO",
2557                "outside_rth": "UnknownOutsideRth",
2558                "price": "11.900",
2559                "quantity": "200",
2560                "side": "Buy",
2561                "status": "RejectedStatus",
2562                "stock_name": "Bank of East Asia Ltd/The",
2563                "submitted_at": "1651644897",
2564                "symbol": "23.HK",
2565                "tag": "Normal",
2566                "time_in_force": "Day",
2567                "trailing_amount": "",
2568                "trailing_percent": "",
2569                "trigger_at": "0",
2570                "trigger_price": "",
2571                "trigger_status": "NOT_USED",
2572                "updated_at": "1651644898",
2573                "limit_depth_level": 0,
2574                "trigger_count": 0,
2575                "monitor_price": "",
2576                "remark": "abc",
2577                "delayed_until": "1767225600"
2578              }
2579            ]
2580          }
2581        "#;
2582
2583        #[derive(Deserialize)]
2584        struct Response {
2585            orders: Vec<Order>,
2586        }
2587
2588        let resp: Response = serde_json::from_str(data).unwrap();
2589        assert_eq!(resp.orders.len(), 1);
2590
2591        let order = &resp.orders[0];
2592        assert_eq!(order.currency, "HKD");
2593        assert!(order.executed_price.is_none());
2594        assert_eq!(order.executed_quantity, decimal!(0));
2595        assert!(order.expire_date.is_none());
2596        assert!(order.last_done.is_none());
2597        assert!(order.limit_offset.is_none());
2598        assert_eq!(order.msg, "");
2599        assert_eq!(order.order_id, "706388312699592704");
2600        assert_eq!(order.order_type, OrderType::ELO);
2601        assert!(order.outside_rth.is_none());
2602        assert_eq!(order.price, Some("11.900".parse().unwrap()));
2603        assert_eq!(order.quantity, decimal!(200));
2604        assert_eq!(order.side, OrderSide::Buy);
2605        assert_eq!(order.status, OrderStatus::Rejected);
2606        assert_eq!(order.stock_name, "Bank of East Asia Ltd/The");
2607        assert_eq!(order.submitted_at, datetime!(2022-05-04 14:14:57 +8));
2608        assert_eq!(order.symbol, "23.HK");
2609        assert_eq!(order.tag, OrderTag::Normal);
2610        assert_eq!(order.time_in_force, TimeInForceType::Day);
2611        assert!(order.trailing_amount.is_none());
2612        assert!(order.trailing_percent.is_none());
2613        assert!(order.trigger_at.is_none());
2614        assert!(order.trigger_price.is_none());
2615        assert!(order.trigger_status.is_none());
2616        assert_eq!(order.updated_at, Some(datetime!(2022-05-04 14:14:58 +8)));
2617        assert_eq!(order.remark, "abc");
2618        assert_eq!(order.delayed_until, Some(datetime!(2026-01-01 00:00 UTC)));
2619    }
2620
2621    #[test]
2622    fn today_orders() {
2623        let data = r#"
2624        {
2625            "orders": [
2626              {
2627                "currency": "HKD",
2628                "executed_price": "0.000",
2629                "executed_quantity": "0",
2630                "expire_date": "",
2631                "last_done": "",
2632                "limit_offset": "",
2633                "msg": "",
2634                "order_id": "706388312699592704",
2635                "order_type": "ELO",
2636                "outside_rth": "UnknownOutsideRth",
2637                "price": "11.900",
2638                "quantity": "200",
2639                "side": "Buy",
2640                "status": "RejectedStatus",
2641                "stock_name": "Bank of East Asia Ltd/The",
2642                "submitted_at": "1651644897",
2643                "symbol": "23.HK",
2644                "tag": "Normal",
2645                "time_in_force": "Day",
2646                "trailing_amount": "",
2647                "trailing_percent": "",
2648                "trigger_at": "0",
2649                "trigger_price": "",
2650                "trigger_status": "NOT_USED",
2651                "updated_at": "1651644898",
2652                "limit_depth_level": 0,
2653                "trigger_count": 0,
2654                "monitor_price": "",
2655                "remark": "abc"
2656              }
2657            ]
2658          }
2659        "#;
2660
2661        #[derive(Deserialize)]
2662        struct Response {
2663            orders: Vec<Order>,
2664        }
2665
2666        let resp: Response = serde_json::from_str(data).unwrap();
2667        assert_eq!(resp.orders.len(), 1);
2668
2669        let order = &resp.orders[0];
2670        assert_eq!(order.currency, "HKD");
2671        assert!(order.executed_price.is_none());
2672        assert_eq!(order.executed_quantity, decimal!(0));
2673        assert!(order.expire_date.is_none());
2674        assert!(order.last_done.is_none());
2675        assert!(order.limit_offset.is_none());
2676        assert_eq!(order.msg, "");
2677        assert_eq!(order.order_id, "706388312699592704");
2678        assert_eq!(order.order_type, OrderType::ELO);
2679        assert!(order.outside_rth.is_none());
2680        assert_eq!(order.price, Some("11.900".parse().unwrap()));
2681        assert_eq!(order.quantity, decimal!(200));
2682        assert_eq!(order.side, OrderSide::Buy);
2683        assert_eq!(order.status, OrderStatus::Rejected);
2684        assert_eq!(order.stock_name, "Bank of East Asia Ltd/The");
2685        assert_eq!(order.submitted_at, datetime!(2022-05-04 14:14:57 +8));
2686        assert_eq!(order.symbol, "23.HK");
2687        assert_eq!(order.tag, OrderTag::Normal);
2688        assert_eq!(order.time_in_force, TimeInForceType::Day);
2689        assert!(order.trailing_amount.is_none());
2690        assert!(order.trailing_percent.is_none());
2691        assert!(order.trigger_at.is_none());
2692        assert!(order.trigger_price.is_none());
2693        assert!(order.trigger_status.is_none());
2694        assert_eq!(order.updated_at, Some(datetime!(2022-05-04 14:14:58 +8)));
2695        assert_eq!(order.remark, "abc");
2696        assert!(order.delayed_until.is_none());
2697    }
2698
2699    #[test]
2700    fn history_executions() {
2701        let data = r#"
2702        {
2703            "has_more": false,
2704            "trades": [
2705              {
2706                "order_id": "693664675163312128",
2707                "price": "388",
2708                "quantity": "100",
2709                "symbol": "700.HK",
2710                "trade_done_at": "1648611351",
2711                "trade_id": "693664675163312128-1648611351433741210",
2712                "side": "Buy"
2713              }
2714            ]
2715          }
2716        "#;
2717
2718        #[derive(Deserialize)]
2719        struct Response {
2720            trades: Vec<Execution>,
2721        }
2722
2723        let resp: Response = serde_json::from_str(data).unwrap();
2724        assert_eq!(resp.trades.len(), 1);
2725
2726        let execution = &resp.trades[0];
2727        assert_eq!(execution.order_id, "693664675163312128");
2728        assert_eq!(execution.price, "388".parse().unwrap());
2729        assert_eq!(execution.quantity, decimal!(100));
2730        assert_eq!(execution.symbol, "700.HK");
2731        assert_eq!(execution.trade_done_at, datetime!(2022-03-30 11:35:51 +8));
2732        assert_eq!(execution.trade_id, "693664675163312128-1648611351433741210");
2733        assert_eq!(execution.side, OrderSide::Buy);
2734    }
2735
2736    #[test]
2737    fn order_detail() {
2738        let data = r#"
2739        {
2740            "order_id": "828940451093708800",
2741            "status": "FilledStatus",
2742            "stock_name": "Apple",
2743            "quantity": "10",
2744            "executed_quantity": "10",
2745            "price": "200.000",
2746            "executed_price": "164.660",
2747            "submitted_at": "1680863604",
2748            "side": "Buy",
2749            "symbol": "AAPL.US",
2750            "order_type": "LO",
2751            "last_done": "164.660",
2752            "trigger_price": "0.0000",
2753            "msg": "",
2754            "tag": "Normal",
2755            "time_in_force": "Day",
2756            "expire_date": "2023-04-10",
2757            "updated_at": "1681113000",
2758            "trigger_at": "0",
2759            "trailing_amount": "",
2760            "trailing_percent": "",
2761            "limit_offset": "",
2762            "trigger_status": "NOT_USED",
2763            "outside_rth": "ANY_TIME",
2764            "currency": "USD",
2765            "limit_depth_level": 0,
2766            "trigger_count": 0,
2767            "monitor_price": "",
2768            "remark": "1680863603.927165",
2769            "delayed_until": "0",
2770            "free_status": "None",
2771            "free_amount": "",
2772            "free_currency": "",
2773            "deductions_status": "NONE",
2774            "deductions_amount": "",
2775            "deductions_currency": "",
2776            "platform_deducted_status": "NONE",
2777            "platform_deducted_amount": "",
2778            "platform_deducted_currency": "",
2779            "history": [{
2780                "price": "164.6600",
2781                "quantity": "10",
2782                "status": "FilledStatus",
2783                "msg": "Execution of 10",
2784                "time": "1681113000"
2785            }, {
2786                "price": "200.0000",
2787                "quantity": "10",
2788                "status": "NewStatus",
2789                "msg": "",
2790                "time": "1681113000"
2791            }],
2792            "charge_detail": {
2793                "items": [{
2794                    "code": "BROKER_FEES",
2795                    "name": "Broker Fees",
2796                    "fees": []
2797                }, {
2798                    "code": "THIRD_FEES",
2799                    "name": "Third-party Fees",
2800                    "fees": []
2801                }],
2802                "total_amount": "0",
2803                "currency": "USD"
2804            }
2805        }
2806        "#;
2807
2808        let detail = serde_json::from_str::<OrderDetail>(data).unwrap();
2809        assert!(
2810            detail.delayed_until.is_none(),
2811            "\"0\" means no time condition"
2812        );
2813
2814        let mut value: serde_json::Value = serde_json::from_str(data).unwrap();
2815        value["status"] = "DelayedNotReported".into();
2816        value["delayed_until"] = "1767225600".into();
2817        let detail = serde_json::from_value::<OrderDetail>(value).unwrap();
2818        assert_eq!(detail.status, OrderStatus::DelayedNotReported);
2819        assert_eq!(detail.delayed_until, Some(datetime!(2026-01-01 00:00 UTC)));
2820
2821        // The spec marks delayed_until nullable.
2822        let mut value: serde_json::Value = serde_json::from_str(data).unwrap();
2823        value["delayed_until"] = serde_json::Value::Null;
2824        let detail = serde_json::from_value::<OrderDetail>(value).unwrap();
2825        assert!(detail.delayed_until.is_none());
2826
2827        // A malformed value in this new field must not fail the whole response.
2828        for (raw, expected) in [
2829            (
2830                serde_json::json!(1767225600),
2831                Some(datetime!(2026-01-01 00:00 UTC)),
2832            ),
2833            (serde_json::json!("abc"), None),
2834            (serde_json::json!("99999999999999"), None),
2835            (serde_json::json!(""), None),
2836            (serde_json::json!("-5"), None),
2837        ] {
2838            let mut value: serde_json::Value = serde_json::from_str(data).unwrap();
2839            value["delayed_until"] = raw.clone();
2840            let detail = serde_json::from_value::<OrderDetail>(value).unwrap();
2841            assert_eq!(detail.delayed_until, expected, "{raw}");
2842        }
2843    }
2844
2845    #[test]
2846    fn attached_order_limit_depth_level() {
2847        let data = r#"
2848        {
2849            "order_id": "706388312699592705",
2850            "attached_type_display": "STOP_LOSS",
2851            "trigger_price": "10.500",
2852            "quantity": "200",
2853            "executed_qty": "0",
2854            "status": "NewStatus",
2855            "updated_at": "1651644898",
2856            "withdrawn": false,
2857            "gtd": "",
2858            "time_in_force": "Day",
2859            "counter_id": "",
2860            "trigger_status": "NOT_USED",
2861            "executed_amount": "0",
2862            "tag": "Normal",
2863            "submitted_at": "1651644897",
2864            "executed_price": "0.000",
2865            "force_only_rth": "RTH_ONLY",
2866            "reviewed": false,
2867            "activate_order_type": "MIT",
2868            "activate_rth": "RTH_ONLY",
2869            "submit_price": "",
2870            "limit_depth_level": 0
2871        }
2872        "#;
2873        for (raw, expected) in [
2874            (serde_json::json!(0), None),
2875            (serde_json::json!(3), Some(3)),
2876            (serde_json::json!(-2), Some(-2)),
2877            (serde_json::json!("3"), Some(3)),
2878            (serde_json::json!("abc"), None),
2879            (serde_json::Value::Null, None),
2880        ] {
2881            let mut value: serde_json::Value = serde_json::from_str(data).unwrap();
2882            value["limit_depth_level"] = raw.clone();
2883            let detail = serde_json::from_value::<AttachedOrderDetail>(value).unwrap();
2884            assert_eq!(detail.limit_depth_level, expected, "{raw}");
2885        }
2886
2887        // Responses that predate the field still deserialize.
2888        let mut value: serde_json::Value = serde_json::from_str(data).unwrap();
2889        value.as_object_mut().unwrap().remove("limit_depth_level");
2890        let detail = serde_json::from_value::<AttachedOrderDetail>(value).unwrap();
2891        assert!(detail.limit_depth_level.is_none());
2892    }
2893
2894    #[test]
2895    fn risk_assessment_decode() {
2896        // Real test-env response (2026-11-16).
2897        let ra: RiskAssessment = serde_json::from_str(
2898            r#"{"approvals":{"car":"pass","cka":"pass","is_corporate_client":"false","risk_audit":"pass"},
2899                "deadlines":{},"pi":0,"pi_end_at":"0","re_authentication":"","risk":"A5",
2900                "risk_assessment_at":"2026-10-14","score":0,"strategy_risk_levels":[]}"#,
2901        )
2902        .unwrap();
2903        assert_eq!(ra.risk, "A5");
2904        assert_eq!(ra.pi, 0);
2905        assert_eq!(ra.pi_end_at, 0);
2906        assert_eq!(ra.re_authentication, "");
2907        assert_eq!(ra.risk_assessment_at, "2026-10-14");
2908        assert_eq!(ra.score, 0);
2909        assert!(ra.strategy_risk_levels.is_empty());
2910        assert!(ra.deadlines.is_empty());
2911        assert_eq!(ra.approvals.len(), 4);
2912        assert_eq!(ra.approvals["car"], "pass");
2913        assert_eq!(ra.approvals["is_corporate_client"], "false");
2914
2915        // int64 as strings or numbers, int32 as strings, non-string approval
2916        // values, null list.
2917        let ra: RiskAssessment = serde_json::from_str(
2918            r#"{"risk":"R1","pi":"1","pi_end_at":1790000000,"score":"42",
2919                "deadlines":{"pi":"1790000000","risk":1790000001,"x":null},
2920                "approvals":{"flag":true,"n":3},"strategy_risk_levels":null}"#,
2921        )
2922        .unwrap();
2923        assert_eq!(ra.pi, 1);
2924        assert_eq!(ra.pi_end_at, 1790000000);
2925        assert_eq!(ra.score, 42);
2926        assert_eq!(ra.deadlines["pi"], 1790000000);
2927        assert_eq!(ra.deadlines["risk"], 1790000001);
2928        assert_eq!(ra.deadlines["x"], 0);
2929        assert_eq!(ra.approvals["flag"], "true");
2930        assert_eq!(ra.approvals["n"], "3");
2931        assert!(ra.strategy_risk_levels.is_empty());
2932
2933        // Floats, out-of-range ints and non-numeric strings become 0;
2934        // non-string string fields render as JSON text; null list elements
2935        // become empty strings.
2936        let ra: RiskAssessment = serde_json::from_str(
2937            r#"{"risk":5,"re_authentication":true,"risk_assessment_at":null,"pi":1.5,
2938                "score":3000000000,"pi_end_at":1.79e9,
2939                "deadlines":{"a":-2,"b":-2.7,"c":"x","d":18446744073709551615},
2940                "approvals":{"o":{"b":1,"a":2}},"strategy_risk_levels":["S1",null,3]}"#,
2941        )
2942        .unwrap();
2943        assert_eq!(ra.risk, "5");
2944        assert_eq!(ra.re_authentication, "true");
2945        assert_eq!(ra.risk_assessment_at, "");
2946        assert_eq!((ra.pi, ra.score, ra.pi_end_at), (0, 0, 0));
2947        assert_eq!(
2948            ra.deadlines.into_iter().collect::<Vec<_>>(),
2949            vec![
2950                ("a".to_string(), -2),
2951                ("b".to_string(), 0),
2952                ("c".to_string(), 0),
2953                ("d".to_string(), 0)
2954            ]
2955        );
2956        assert_eq!(ra.approvals["o"], r#"{"a":2,"b":1}"#);
2957        assert_eq!(ra.strategy_risk_levels, vec!["S1", "", "3"]);
2958
2959        // Maps serialize in key order.
2960        let ra: RiskAssessment =
2961            serde_json::from_str(r#"{"approvals":{"z":"1","a":"2","m":"3"}}"#).unwrap();
2962        let json = serde_json::to_string(&ra).unwrap();
2963        assert!(json.contains(r#""approvals":{"a":"2","m":"3","z":"1"}"#));
2964
2965        // Wrong-shaped maps and lists become empty instead of failing the call.
2966        let ra: RiskAssessment = serde_json::from_str(
2967            r#"{"approvals":[],"deadlines":"x","strategy_risk_levels":{"a":1}}"#,
2968        )
2969        .unwrap();
2970        assert!(ra.approvals.is_empty() && ra.deadlines.is_empty());
2971        assert!(ra.strategy_risk_levels.is_empty());
2972        let ra: RiskAssessment = serde_json::from_str(r#"{"strategy_risk_levels":"S1"}"#).unwrap();
2973        assert!(ra.strategy_risk_levels.is_empty());
2974
2975        // Empty object and null maps still decode.
2976        let ra: RiskAssessment =
2977            serde_json::from_str(r#"{"approvals":null,"deadlines":null}"#).unwrap();
2978        assert!(ra.risk.is_empty());
2979        assert_eq!(ra.score, 0);
2980        assert!(ra.approvals.is_empty() && ra.deadlines.is_empty());
2981    }
2982}