Skip to main content

longport/trade/
context.rs

1use std::sync::Arc;
2
3use longport_httpcli::{DcRegion, HttpClient, Json, Method};
4use longport_wscli::WsClientError;
5use rust_decimal::Decimal;
6use serde::{Deserialize, Serialize};
7use tokio::sync::{mpsc, oneshot};
8use tracing::{Subscriber, dispatcher, instrument::WithSubscriber};
9
10use crate::{
11    Config, Result, serde_utils,
12    trade::{
13        AccountBalance, CancelOrderOptions, CashFlow, EstimateMaxPurchaseQuantityOptions,
14        Execution, FundPositionsResponse, GetCashFlowOptions, GetFundPositionsOptions,
15        GetHistoryExecutionsOptions, GetHistoryOrdersOptions, GetOrderDetailOptions,
16        GetStockPositionsOptions, GetTodayExecutionsOptions, GetTodayOrdersOptions,
17        GetUSAvailableHoldingOptions, GetUSHistoryOrders, GetUSRealizedPLOptions,
18        GetUSTransactionHistoryOptions, MarginRatio, Order, OrderDetail, OrderSide, PushEvent,
19        QueryUSOrdersResponse, ReplaceOrderOptions, RiskAssessment, StockPositionsResponse,
20        SubmitMultiLegOrderOptions, SubmitOrderOptions, TopicType, USAssetOverview,
21        USAvailableHolding, USCashAndBuyPower, USExchangeRates, USOrderDetailResponse,
22        USRealizedPL, USTransactionHistory,
23        core::{Command, Core},
24    },
25    types::normalize_symbol_owned,
26};
27
28#[derive(Debug, Deserialize)]
29struct EmptyResponse {}
30
31/// Response for submit order request
32#[derive(Debug, Serialize, Deserialize)]
33pub struct SubmitOrderResponse {
34    /// Order id
35    pub order_id: String,
36}
37
38/// Response for estimate maximum purchase quantity
39#[derive(Debug, Serialize, Deserialize)]
40pub struct EstimateMaxPurchaseQuantityResponse {
41    /// Cash available quantity
42    #[serde(with = "serde_utils::decimal_empty_is_0")]
43    pub cash_max_qty: Decimal,
44    /// Margin available quantity
45    #[serde(with = "serde_utils::decimal_empty_is_0")]
46    pub margin_max_qty: Decimal,
47}
48
49struct InnerTradeContext {
50    command_tx: mpsc::UnboundedSender<Command>,
51    http_cli: HttpClient,
52    log_subscriber: Arc<dyn Subscriber + Send + Sync>,
53    /// Kept alive only so the background `Core::run` task can observe the
54    /// context being dropped (via this channel closing) and stop reconnecting.
55    _shutdown_tx: mpsc::UnboundedSender<()>,
56}
57
58impl Drop for InnerTradeContext {
59    fn drop(&mut self) {
60        dispatcher::with_default(&self.log_subscriber.clone().into(), || {
61            tracing::info!("trade context dropped");
62        });
63    }
64}
65
66/// Trade context
67#[derive(Clone)]
68pub struct TradeContext(Arc<InnerTradeContext>);
69
70impl TradeContext {
71    /// Create a `TradeContext`
72    pub fn new(config: Arc<Config>) -> (Self, mpsc::UnboundedReceiver<PushEvent>) {
73        let log_subscriber = config.create_log_subscriber("trade");
74
75        dispatcher::with_default(&log_subscriber.clone().into(), || {
76            tracing::info!(language = ?config.language, "creating trade context");
77        });
78
79        let http_cli = config.create_http_client();
80        let (command_tx, command_rx) = mpsc::unbounded_channel();
81        let (push_tx, push_rx) = mpsc::unbounded_channel();
82        let (shutdown_tx, shutdown_rx) = mpsc::unbounded_channel();
83        let core = Core::new(config, command_rx, push_tx);
84        crate::runtime::RUNTIME.handle().spawn(
85            core.run(shutdown_rx)
86                .with_subscriber(log_subscriber.clone()),
87        );
88
89        dispatcher::with_default(&log_subscriber.clone().into(), || {
90            tracing::info!("trade context created");
91        });
92
93        (
94            TradeContext(Arc::new(InnerTradeContext {
95                http_cli,
96                command_tx,
97                log_subscriber,
98                _shutdown_tx: shutdown_tx,
99            })),
100            push_rx,
101        )
102    }
103
104    /// Returns the log subscriber
105    #[inline]
106    pub fn log_subscriber(&self) -> Arc<dyn Subscriber + Send + Sync> {
107        self.0.log_subscriber.clone()
108    }
109
110    /// Subscribe
111    ///
112    /// Reference: <https://open.longportapp.com/en/docs/trade/trade-push#subscribe>
113    ///
114    /// # Examples
115    ///
116    /// ```no_run
117    /// use std::sync::Arc;
118    ///
119    /// use longport::{
120    ///     Config, decimal,
121    ///     oauth::OAuthBuilder,
122    ///     trade::{OrderSide, OrderType, SubmitOrderOptions, TimeInForceType, TradeContext},
123    /// };
124    ///
125    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
126    /// let oauth = OAuthBuilder::new("your-client-id")
127    ///     .build(|url| println!("Visit: {url}"))
128    ///     .await?;
129    /// let config = Arc::new(Config::from_oauth(oauth));
130    /// let (ctx, mut receiver) = TradeContext::new(config);
131    ///
132    /// let opts = SubmitOrderOptions::new(
133    ///     "700.HK",
134    ///     OrderType::LO,
135    ///     OrderSide::Buy,
136    ///     decimal!(200),
137    ///     TimeInForceType::Day,
138    /// )
139    /// .submitted_price(decimal!(50i32));
140    /// let resp = ctx.submit_order(opts).await?;
141    /// println!("{:?}", resp);
142    ///
143    /// while let Some(event) = receiver.recv().await {
144    ///     println!("{:?}", event);
145    /// }
146    ///
147    /// # Ok::<_, Box<dyn std::error::Error>>(())
148    /// # });
149    /// ```
150    pub async fn subscribe<I>(&self, topics: I) -> Result<()>
151    where
152        I: IntoIterator<Item = TopicType>,
153    {
154        let (reply_tx, reply_rx) = oneshot::channel();
155        self.0
156            .command_tx
157            .send(Command::Subscribe {
158                topics: topics.into_iter().collect(),
159                reply_tx,
160            })
161            .map_err(|_| WsClientError::ClientClosed)?;
162        reply_rx.await.map_err(|_| WsClientError::ClientClosed)?
163    }
164
165    /// Unsubscribe
166    ///
167    /// Reference: <https://open.longportapp.com/en/docs/trade/trade-push#cancel-subscribe>
168    pub async fn unsubscribe<I>(&self, topics: I) -> Result<()>
169    where
170        I: IntoIterator<Item = TopicType>,
171    {
172        let (reply_tx, reply_rx) = oneshot::channel();
173        self.0
174            .command_tx
175            .send(Command::Unsubscribe {
176                topics: topics.into_iter().collect(),
177                reply_tx,
178            })
179            .map_err(|_| WsClientError::ClientClosed)?;
180        reply_rx.await.map_err(|_| WsClientError::ClientClosed)?
181    }
182
183    /// Get history executions
184    ///
185    /// `side` may be `Unknown` on LongPort US accounts.
186    ///
187    /// Reference: <https://open.longportapp.com/en/docs/trade/execution/history_executions>
188    ///
189    /// # Examples
190    ///
191    /// ```no_run
192    /// use std::sync::Arc;
193    ///
194    /// use longport::{
195    ///     oauth::OAuthBuilder,
196    ///     trade::{GetHistoryExecutionsOptions, TradeContext},
197    ///     Config,
198    /// };
199    /// use time::macros::datetime;
200    ///
201    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
202    /// let oauth = OAuthBuilder::new("your-client-id")
203    ///     .build(|url| println!("Visit: {url}"))
204    ///     .await?;
205    /// let config = Arc::new(Config::from_oauth(oauth));
206    /// let (ctx, _) = TradeContext::new(config);
207    ///
208    /// let opts = GetHistoryExecutionsOptions::new()
209    ///     .symbol("700.HK")
210    ///     .start_at(datetime!(2022-05-09 0:00 UTC))
211    ///     .end_at(datetime!(2022-05-12 0:00 UTC));
212    /// let resp = ctx.history_executions(opts).await?;
213    /// println!("{:?}", resp);
214    /// # Ok::<_, Box<dyn std::error::Error>>(())
215    /// # });
216    /// ```
217    pub async fn history_executions(
218        &self,
219        options: impl Into<Option<GetHistoryExecutionsOptions>>,
220    ) -> Result<Vec<Execution>> {
221        use std::collections::HashSet;
222
223        #[derive(Deserialize)]
224        struct Response {
225            #[serde(default)]
226            has_more: bool,
227            trades: Vec<Execution>,
228        }
229
230        // The endpoint caps each response at 1000 records; walk the `page`
231        // param (1-based) until `has_more` is false. Dedupe by
232        // `trade_id` and stop if a page adds nothing new, guarding
233        // against the gateway ignoring `page`. Bounded to 1000 pages as
234        // a runaway guard.
235        let mut options = options.into().unwrap_or_default();
236        let mut all: Vec<Execution> = Vec::new();
237        let mut seen: HashSet<String> = HashSet::new();
238        for page in 1..=1000u32 {
239            options = options.with_page(page);
240            let resp = self
241                .0
242                .http_cli
243                .request(Method::GET, "/v1/trade/execution/history")
244                .query_params(&options)
245                .response::<Json<Response>>()
246                .send()
247                .with_subscriber(self.0.log_subscriber.clone())
248                .await?
249                .0;
250            if resp.trades.is_empty() {
251                break;
252            }
253            let mut added = 0usize;
254            for t in resp.trades {
255                if seen.insert(t.trade_id.clone()) {
256                    all.push(t);
257                    added += 1;
258                }
259            }
260            if !resp.has_more || added == 0 {
261                break;
262            }
263        }
264        Ok(all)
265    }
266
267    /// Get today executions
268    ///
269    /// Reference: <https://open.longportapp.com/en/docs/trade/execution/today_executions>
270    ///
271    /// # Examples
272    ///
273    /// ```no_run
274    /// use std::sync::Arc;
275    ///
276    /// use longport::{
277    ///     Config,
278    ///     oauth::OAuthBuilder,
279    ///     trade::{GetTodayExecutionsOptions, TradeContext},
280    /// };
281    ///
282    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
283    /// let oauth = OAuthBuilder::new("your-client-id")
284    ///     .build(|url| println!("Visit: {url}"))
285    ///     .await?;
286    /// let config = Arc::new(Config::from_oauth(oauth));
287    /// let (ctx, _) = TradeContext::new(config);
288    ///
289    /// let opts = GetTodayExecutionsOptions::new().symbol("700.HK");
290    /// let resp = ctx.today_executions(opts).await?;
291    /// println!("{:?}", resp);
292    /// # Ok::<_, Box<dyn std::error::Error>>(())
293    /// # });
294    /// ```
295    pub async fn today_executions(
296        &self,
297        options: impl Into<Option<GetTodayExecutionsOptions>>,
298    ) -> Result<Vec<Execution>> {
299        #[derive(Deserialize)]
300        struct Response {
301            trades: Vec<Execution>,
302        }
303
304        Ok(self
305            .0
306            .http_cli
307            .request(Method::GET, "/v1/trade/execution/today")
308            .query_params(options.into().unwrap_or_default())
309            .response::<Json<Response>>()
310            .send()
311            .with_subscriber(self.0.log_subscriber.clone())
312            .await?
313            .0
314            .trades)
315    }
316
317    // TODO: temporarily disabled — restore when API is available
318    // Get all executions
319    //
320    // AP accounts only: US data-center accounts get a region error; use
321    // `history_executions` instead.
322    //
323    // Reference: <https://open.longportapp.com/en/docs/trade/execution/all_executions>
324    // pub async fn all_executions(
325    // &self,
326    // options: impl Into<Option<GetAllExecutionsOptions>>,
327    // ) -> Result<AllExecutionsResponse> {
328    // Ok(self
329    // .0
330    // .http_cli
331    // .request(Method::GET, "/v3/trade/execution/all")
332    // .dc_restrict(DcRegion::Ap)
333    // .query_params(options.into().unwrap_or_default())
334    // .response::<Json<AllExecutionsResponse>>()
335    // .send()
336    // .with_subscriber(self.0.log_subscriber.clone())
337    // .await?
338    // .0)
339    // }
340
341    /// Get history orders
342    ///
343    /// Reference: <https://open.longportapp.com/en/docs/trade/order/history_orders>
344    ///
345    /// # Examples
346    ///
347    /// ```no_run
348    /// use std::sync::Arc;
349    ///
350    /// use longport::{
351    ///     oauth::OAuthBuilder,
352    ///     trade::{GetHistoryOrdersOptions, OrderSide, OrderStatus, TradeContext},
353    ///     Config, Market,
354    /// };
355    /// use time::macros::datetime;
356    ///
357    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
358    /// let oauth = OAuthBuilder::new("your-client-id")
359    ///     .build(|url| println!("Visit: {url}"))
360    ///     .await?;
361    /// let config = Arc::new(Config::from_oauth(oauth));
362    /// let (ctx, _) = TradeContext::new(config);
363    ///
364    /// let opts = GetHistoryOrdersOptions::new()
365    ///     .symbol("700.HK")
366    ///     .status([OrderStatus::Filled, OrderStatus::New])
367    ///     .side(OrderSide::Buy)
368    ///     .market(Market::HK)
369    ///     .start_at(datetime!(2022-05-09 0:00 UTC))
370    ///     .end_at(datetime!(2022-05-12 0:00 UTC));
371    /// let resp = ctx.history_orders(opts).await?;
372    /// println!("{:?}", resp);
373    /// # Ok::<_, Box<dyn std::error::Error>>(())
374    /// # });
375    /// ```
376    pub async fn history_orders(
377        &self,
378        options: impl Into<Option<GetHistoryOrdersOptions>>,
379    ) -> Result<Vec<Order>> {
380        use std::collections::HashSet;
381
382        #[derive(Deserialize)]
383        struct Response {
384            orders: Vec<Order>,
385            #[serde(default)]
386            has_more: bool,
387        }
388
389        // The endpoint caps each response at 1000 records and reports the
390        // overflow in `has_more`; walk the `page` param (1-based) until it is
391        // false. Dedupe by `order_id` and stop if a page adds nothing new,
392        // guarding against the gateway ignoring `page`. Bounded to 1000 pages
393        // as a runaway guard. Mirrors `history_executions`.
394        let mut options = options.into().unwrap_or_default();
395        let mut all: Vec<Order> = Vec::new();
396        let mut seen: HashSet<String> = HashSet::new();
397        for page in 1..=1000u32 {
398            options = options.with_page(page);
399            let resp = self
400                .0
401                .http_cli
402                .request(Method::GET, "/v1/trade/order/history")
403                .query_params(&options)
404                .response::<Json<Response>>()
405                .send()
406                .with_subscriber(self.0.log_subscriber.clone())
407                .await?
408                .0;
409            if resp.orders.is_empty() {
410                break;
411            }
412            let mut added = 0usize;
413            for o in resp.orders {
414                if seen.insert(o.order_id.clone()) {
415                    all.push(o);
416                    added += 1;
417                }
418            }
419            if !resp.has_more || added == 0 {
420                break;
421            }
422        }
423        Ok(all)
424    }
425
426    /// Get today orders
427    ///
428    /// Reference: <https://open.longportapp.com/en/docs/trade/order/today_orders>
429    ///
430    /// # Examples
431    ///
432    /// ```no_run
433    /// use std::sync::Arc;
434    ///
435    /// use longport::{
436    ///     Config, Market,
437    ///     oauth::OAuthBuilder,
438    ///     trade::{GetTodayOrdersOptions, OrderSide, OrderStatus, TradeContext},
439    /// };
440    ///
441    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
442    /// let oauth = OAuthBuilder::new("your-client-id")
443    ///     .build(|url| println!("Visit: {url}"))
444    ///     .await?;
445    /// let config = Arc::new(Config::from_oauth(oauth));
446    /// let (ctx, _) = TradeContext::new(config);
447    ///
448    /// let opts = GetTodayOrdersOptions::new()
449    ///     .symbol("700.HK")
450    ///     .status([OrderStatus::Filled, OrderStatus::New])
451    ///     .side(OrderSide::Buy)
452    ///     .market(Market::HK);
453    /// let resp = ctx.today_orders(opts).await?;
454    /// println!("{:?}", resp);
455    /// # Ok::<_, Box<dyn std::error::Error>>(())
456    /// # });
457    /// ```
458    pub async fn today_orders(
459        &self,
460        options: impl Into<Option<GetTodayOrdersOptions>>,
461    ) -> Result<Vec<Order>> {
462        #[derive(Deserialize)]
463        struct Response {
464            orders: Vec<Order>,
465        }
466
467        Ok(self
468            .0
469            .http_cli
470            .request(Method::GET, "/v1/trade/order/today")
471            .query_params(options.into().unwrap_or_default())
472            .response::<Json<Response>>()
473            .send()
474            .with_subscriber(self.0.log_subscriber.clone())
475            .await?
476            .0
477            .orders)
478    }
479
480    /// Replace order
481    ///
482    /// Reference: <https://open.longportapp.com/en/docs/trade/order/replace>
483    ///
484    /// # Examples
485    ///
486    /// ```no_run
487    /// use std::sync::Arc;
488    ///
489    /// use longport::{
490    ///     Config, decimal,
491    ///     oauth::OAuthBuilder,
492    ///     trade::{ReplaceOrderOptions, TradeContext},
493    /// };
494    ///
495    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
496    /// let oauth = OAuthBuilder::new("your-client-id")
497    ///     .build(|url| println!("Visit: {url}"))
498    ///     .await?;
499    /// let config = Arc::new(Config::from_oauth(oauth));
500    /// let (ctx, _) = TradeContext::new(config);
501    ///
502    /// let opts =
503    ///     ReplaceOrderOptions::new("709043056541253632", decimal!(100)).price(decimal!(300i32));
504    /// let resp = ctx.replace_order(opts).await?;
505    /// println!("{:?}", resp);
506    /// # Ok::<_, Box<dyn std::error::Error>>(())
507    /// # });
508    /// ```
509    pub async fn replace_order(&self, options: ReplaceOrderOptions) -> Result<()> {
510        Ok(self
511            .0
512            .http_cli
513            .request(Method::PUT, "/v1/trade/order")
514            .body(Json(options))
515            .response::<Json<EmptyResponse>>()
516            .send()
517            .with_subscriber(self.0.log_subscriber.clone())
518            .await
519            .map(|_| ())?)
520    }
521
522    /// Submit order
523    ///
524    /// Reference: <https://open.longportapp.com/en/docs/trade/order/submit>
525    ///
526    /// # Examples
527    ///
528    /// ```no_run
529    /// use std::sync::Arc;
530    ///
531    /// use longport::{
532    ///     Config, decimal,
533    ///     oauth::OAuthBuilder,
534    ///     trade::{OrderSide, OrderType, SubmitOrderOptions, TimeInForceType, TradeContext},
535    /// };
536    ///
537    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
538    /// let oauth = OAuthBuilder::new("your-client-id")
539    ///     .build(|url| println!("Visit: {url}"))
540    ///     .await?;
541    /// let config = Arc::new(Config::from_oauth(oauth));
542    /// let (ctx, _) = TradeContext::new(config);
543    ///
544    /// let opts = SubmitOrderOptions::new(
545    ///     "700.HK",
546    ///     OrderType::LO,
547    ///     OrderSide::Buy,
548    ///     decimal!(200),
549    ///     TimeInForceType::Day,
550    /// )
551    /// .submitted_price(decimal!(50i32));
552    /// let resp = ctx.submit_order(opts).await?;
553    /// println!("{:?}", resp);
554    /// # Ok::<_, Box<dyn std::error::Error>>(())
555    /// # });
556    /// ```
557    pub async fn submit_order(&self, options: SubmitOrderOptions) -> Result<SubmitOrderResponse> {
558        let resp: SubmitOrderResponse = self
559            .0
560            .http_cli
561            .request(Method::POST, "/v1/trade/order")
562            .body(Json(options))
563            .response::<Json<_>>()
564            .send()
565            .with_subscriber(self.0.log_subscriber.clone())
566            .await?
567            .0;
568        _ = self.0.command_tx.send(Command::SubmittedOrder {
569            order_id: resp.order_id.clone(),
570        });
571        Ok(resp)
572    }
573
574    /// Submit a multi-leg option combination order (such as vertical spreads,
575    /// straddles, strangles, collars, etc.). All legs are submitted together
576    /// as a single strategy order.
577    ///
578    /// # Examples
579    ///
580    /// ```no_run
581    /// use std::sync::Arc;
582    ///
583    /// use longport::{
584    ///     Config, decimal,
585    ///     oauth::OAuthBuilder,
586    ///     trade::{
587    ///         MultiLegStrategy, OrderSide, OrderType, SubmitMultiLegOrderLeg,
588    ///         SubmitMultiLegOrderOptions, TradeContext,
589    ///     },
590    /// };
591    ///
592    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
593    /// let oauth = OAuthBuilder::new("your-client-id")
594    ///     .build(|url| println!("Visit: {url}"))
595    ///     .await?;
596    /// let config = Arc::new(Config::from_oauth(oauth));
597    /// let (ctx, _) = TradeContext::new(config);
598    ///
599    /// let opts = SubmitMultiLegOrderOptions::new(
600    ///     OrderSide::Buy,
601    ///     OrderType::LO,
602    ///     decimal!(1i32),
603    ///     MultiLegStrategy::VerticalCallSpread,
604    ///     [
605    ///         SubmitMultiLegOrderLeg::new("QQQ260731C764000.US", decimal!(1i32)),
606    ///         SubmitMultiLegOrderLeg::new("QQQ260731C767000.US", decimal!(1i32)),
607    ///     ],
608    /// )
609    /// .submitted_price(decimal!(1.5));
610    /// let resp = ctx.submit_multileg(opts).await?;
611    /// println!("{:?}", resp);
612    /// # Ok::<_, Box<dyn std::error::Error>>(())
613    /// # });
614    /// ```
615    pub async fn submit_multileg(
616        &self,
617        options: SubmitMultiLegOrderOptions,
618    ) -> Result<SubmitOrderResponse> {
619        let resp: SubmitOrderResponse = self
620            .0
621            .http_cli
622            .request(Method::POST, "/v1/trade/order/multileg")
623            .body(Json(options))
624            .response::<Json<_>>()
625            .send()
626            .with_subscriber(self.0.log_subscriber.clone())
627            .await?
628            .0;
629        _ = self.0.command_tx.send(Command::SubmittedOrder {
630            order_id: resp.order_id.clone(),
631        });
632        Ok(resp)
633    }
634
635    /// Cancel order
636    ///
637    /// Reference: <https://open.longportapp.com/en/docs/trade/order/withdraw>
638    ///
639    /// # Examples
640    ///
641    /// ```no_run
642    /// use std::sync::Arc;
643    ///
644    /// use longport::{Config, oauth::OAuthBuilder, trade::TradeContext};
645    ///
646    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
647    /// let oauth = OAuthBuilder::new("your-client-id")
648    ///     .build(|url| println!("Visit: {url}"))
649    ///     .await?;
650    /// let config = Arc::new(Config::from_oauth(oauth));
651    /// let (ctx, _) = TradeContext::new(config);
652    ///
653    /// ctx.cancel_order("709043056541253632").await?;
654    /// # Ok::<_, Box<dyn std::error::Error>>(())
655    /// # });
656    /// ```
657    pub async fn cancel_order(&self, options: impl Into<CancelOrderOptions>) -> Result<()> {
658        Ok(self
659            .0
660            .http_cli
661            .request(Method::DELETE, "/v1/trade/order")
662            .response::<Json<EmptyResponse>>()
663            .query_params(options.into())
664            .send()
665            .with_subscriber(self.0.log_subscriber.clone())
666            .await
667            .map(|_| ())?)
668    }
669
670    /// Get account balance
671    ///
672    /// AP accounts only: US data-center accounts get a region error; use
673    /// `us_cash_and_buy_power` (or `us_asset_overview`) instead.
674    ///
675    /// Reference: <https://open.longportapp.com/en/docs/trade/asset/account>
676    ///
677    /// # Examples
678    ///
679    /// ```no_run
680    /// use std::sync::Arc;
681    ///
682    /// use longport::{Config, oauth::OAuthBuilder, trade::TradeContext};
683    ///
684    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
685    /// let oauth = OAuthBuilder::new("your-client-id")
686    ///     .build(|url| println!("Visit: {url}"))
687    ///     .await?;
688    /// let config = Arc::new(Config::from_oauth(oauth));
689    /// let (ctx, _) = TradeContext::new(config);
690    ///
691    /// let resp = ctx.account_balance(None).await?;
692    /// println!("{:?}", resp);
693    /// # Ok::<_, Box<dyn std::error::Error>>(())
694    /// # });
695    /// ```
696    pub async fn account_balance(&self, currency: Option<&str>) -> Result<Vec<AccountBalance>> {
697        #[derive(Debug, Serialize)]
698        struct Request<'a> {
699            currency: Option<&'a str>,
700        }
701
702        #[derive(Debug, Deserialize)]
703        struct Response {
704            list: Vec<AccountBalance>,
705        }
706
707        Ok(self
708            .0
709            .http_cli
710            .request(Method::GET, "/v1/asset/account")
711            .dc_restrict(DcRegion::Ap)
712            .query_params(Request { currency })
713            .response::<Json<Response>>()
714            .send()
715            .with_subscriber(self.0.log_subscriber.clone())
716            .await?
717            .0
718            .list)
719    }
720
721    /// Get cash flow
722    ///
723    /// AP accounts only: US data-center accounts get a region error; use
724    /// `us_transaction_history` instead.
725    ///
726    /// Reference: <https://open.longportapp.com/en/docs/trade/asset/cashflow>
727    ///
728    /// # Examples
729    ///
730    /// ```no_run
731    /// use std::sync::Arc;
732    ///
733    /// use longport::{
734    ///     oauth::OAuthBuilder,
735    ///     trade::{GetCashFlowOptions, TradeContext},
736    ///     Config,
737    /// };
738    /// use time::macros::datetime;
739    ///
740    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
741    /// let oauth = OAuthBuilder::new("your-client-id")
742    ///     .build(|url| println!("Visit: {url}"))
743    ///     .await?;
744    /// let config = Arc::new(Config::from_oauth(oauth));
745    /// let (ctx, _) = TradeContext::new(config);
746    ///
747    /// let opts = GetCashFlowOptions::new(datetime!(2022-05-09 0:00 UTC), datetime!(2022-05-12 0:00 UTC));
748    /// let resp = ctx.cash_flow(opts).await?;
749    /// println!("{:?}", resp);
750    /// # Ok::<_, Box<dyn std::error::Error>>(())
751    /// # });
752    /// ```
753    pub async fn cash_flow(&self, options: GetCashFlowOptions) -> Result<Vec<CashFlow>> {
754        #[derive(Debug, Deserialize)]
755        struct Response {
756            list: Vec<CashFlow>,
757        }
758
759        Ok(self
760            .0
761            .http_cli
762            .request(Method::GET, "/v1/asset/cashflow")
763            .dc_restrict(DcRegion::Ap)
764            .query_params(options)
765            .response::<Json<Response>>()
766            .send()
767            .with_subscriber(self.0.log_subscriber.clone())
768            .await?
769            .0
770            .list)
771    }
772
773    /// Get fund positions
774    ///
775    /// Reference: <https://open.longportapp.com/en/docs/trade/asset/fund>
776    ///
777    /// AP accounts only: US data-center accounts have no fund holdings and
778    /// get a region error. No US equivalent.
779    ///
780    /// # Examples
781    ///
782    /// ```no_run
783    /// use std::sync::Arc;
784    ///
785    /// use longport::{Config, oauth::OAuthBuilder, trade::TradeContext};
786    ///
787    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
788    /// let oauth = OAuthBuilder::new("your-client-id")
789    ///     .build(|url| println!("Visit: {url}"))
790    ///     .await?;
791    /// let config = Arc::new(Config::from_oauth(oauth));
792    /// let (ctx, _) = TradeContext::new(config);
793    ///
794    /// let resp = ctx.fund_positions(None).await?;
795    /// println!("{:?}", resp);
796    /// # Ok::<_, Box<dyn std::error::Error>>(())
797    /// # });
798    /// ```
799    pub async fn fund_positions(
800        &self,
801        opts: impl Into<Option<GetFundPositionsOptions>>,
802    ) -> Result<FundPositionsResponse> {
803        Ok(self
804            .0
805            .http_cli
806            .request(Method::GET, "/v1/asset/fund")
807            .dc_restrict(DcRegion::Ap)
808            .query_params(opts.into().unwrap_or_default())
809            .response::<Json<FundPositionsResponse>>()
810            .send()
811            .with_subscriber(self.0.log_subscriber.clone())
812            .await?
813            .0)
814    }
815
816    /// Get stock positions
817    ///
818    /// AP accounts only: US data-center accounts get a region error; use
819    /// `us_asset_overview` (`stock_list`) instead.
820    ///
821    /// Reference: <https://open.longportapp.com/en/docs/trade/asset/stock>
822    ///
823    /// # Examples
824    ///
825    /// ```no_run
826    /// use std::sync::Arc;
827    ///
828    /// use longport::{Config, oauth::OAuthBuilder, trade::TradeContext};
829    ///
830    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
831    /// let oauth = OAuthBuilder::new("your-client-id")
832    ///     .build(|url| println!("Visit: {url}"))
833    ///     .await?;
834    /// let config = Arc::new(Config::from_oauth(oauth));
835    /// let (ctx, _) = TradeContext::new(config);
836    ///
837    /// let resp = ctx.stock_positions(None).await?;
838    /// println!("{:?}", resp);
839    /// # Ok::<_, Box<dyn std::error::Error>>(())
840    /// # });
841    /// ```
842    pub async fn stock_positions(
843        &self,
844        opts: impl Into<Option<GetStockPositionsOptions>>,
845    ) -> Result<StockPositionsResponse> {
846        Ok(self
847            .0
848            .http_cli
849            .request(Method::GET, "/v1/asset/stock")
850            .dc_restrict(DcRegion::Ap)
851            .query_params(opts.into().unwrap_or_default())
852            .response::<Json<StockPositionsResponse>>()
853            .send()
854            .with_subscriber(self.0.log_subscriber.clone())
855            .await?
856            .0)
857    }
858
859    /// Get margin ratio
860    ///
861    /// Reference: <https://open.longportapp.com/en/docs/trade/asset/margin_ratio>
862    ///
863    /// AP accounts only: US data-center accounts get a region error. No US
864    /// equivalent; for US margin info see `us_cash_and_buy_power`
865    /// (`margin_status`).
866    ///
867    /// # Examples
868    ///
869    /// ```no_run
870    /// use std::sync::Arc;
871    ///
872    /// use longport::{Config, oauth::OAuthBuilder, trade::TradeContext};
873    ///
874    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
875    /// let oauth = OAuthBuilder::new("your-client-id")
876    ///     .build(|url| println!("Visit: {url}"))
877    ///     .await?;
878    /// let config = Arc::new(Config::from_oauth(oauth));
879    /// let (ctx, _) = TradeContext::new(config);
880    ///
881    /// let resp = ctx.margin_ratio("700.HK").await?;
882    /// println!("{:?}", resp);
883    /// # Ok::<_, Box<dyn std::error::Error>>(())
884    /// # });
885    /// ```
886    pub async fn margin_ratio(&self, symbol: impl Into<String>) -> Result<MarginRatio> {
887        #[derive(Debug, Serialize)]
888        struct Request {
889            symbol: String,
890        }
891
892        Ok(self
893            .0
894            .http_cli
895            .request(Method::GET, "/v1/risk/margin-ratio")
896            .dc_restrict(DcRegion::Ap)
897            .query_params(Request {
898                symbol: normalize_symbol_owned(symbol),
899            })
900            .response::<Json<MarginRatio>>()
901            .send()
902            .with_subscriber(self.0.log_subscriber.clone())
903            .await?
904            .0)
905    }
906
907    /// Get the risk assessment (suitability questionnaire) result of the
908    /// current member
909    ///
910    /// # Examples
911    ///
912    /// ```no_run
913    /// use std::sync::Arc;
914    ///
915    /// use longport::{Config, oauth::OAuthBuilder, trade::TradeContext};
916    ///
917    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
918    /// let oauth = OAuthBuilder::new("your-client-id")
919    ///     .build(|url| println!("Visit: {url}"))
920    ///     .await?;
921    /// let config = Arc::new(Config::from_oauth(oauth));
922    /// let (ctx, _) = TradeContext::new(config);
923    ///
924    /// let resp = ctx.risk_assessment().await?;
925    /// println!("{:?}", resp);
926    /// # Ok::<_, Box<dyn std::error::Error>>(())
927    /// # });
928    /// ```
929    pub async fn risk_assessment(&self) -> Result<RiskAssessment> {
930        Ok(self
931            .0
932            .http_cli
933            .request(Method::GET, "/v1/members/me/risk-assessment")
934            .response::<Json<RiskAssessment>>()
935            .send()
936            .with_subscriber(self.0.log_subscriber.clone())
937            .await?
938            .0)
939    }
940
941    /// Get order detail
942    ///
943    /// AP accounts only: US data-center accounts get a region error; use
944    /// `us_order_detail` instead.
945    ///
946    /// Reference: <https://open.longportapp.com/en/docs/trade/order/order_detail>
947    ///
948    /// # Examples
949    ///
950    /// ```no_run
951    /// use std::sync::Arc;
952    ///
953    /// use longport::{
954    ///     Config, Market,
955    ///     oauth::OAuthBuilder,
956    ///     trade::{GetHistoryOrdersOptions, OrderSide, OrderStatus, TradeContext},
957    /// };
958    /// use time::macros::datetime;
959    ///
960    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
961    /// let oauth = OAuthBuilder::new("your-client-id")
962    ///     .build(|url| println!("Visit: {url}"))
963    ///     .await?;
964    /// let config = Arc::new(Config::from_oauth(oauth));
965    /// let (ctx, _) = TradeContext::new(config);
966    ///
967    /// let resp = ctx.order_detail("701276261045858304").await?;
968    /// println!("{:?}", resp);
969    /// # Ok::<_, Box<dyn std::error::Error>>(())
970    /// # });
971    /// ```
972    pub async fn order_detail(
973        &self,
974        options: impl Into<GetOrderDetailOptions>,
975    ) -> Result<OrderDetail> {
976        Ok(self
977            .0
978            .http_cli
979            .request(Method::GET, "/v1/trade/order")
980            .dc_restrict(DcRegion::Ap)
981            .response::<Json<OrderDetail>>()
982            .query_params(options.into())
983            .send()
984            .with_subscriber(self.0.log_subscriber.clone())
985            .await?
986            .0)
987    }
988
989    /// Estimating the maximum purchase quantity for Hong Kong and US stocks,
990    /// warrants, and options
991    ///
992    ///
993    /// Reference: <https://open.longportapp.com/en/docs/trade/order/estimate_available_buy_limit>
994    ///
995    /// # Examples
996    ///
997    /// ```no_run
998    /// use std::sync::Arc;
999    ///
1000    /// use longport::{
1001    ///     Config,
1002    ///     oauth::OAuthBuilder,
1003    ///     trade::{EstimateMaxPurchaseQuantityOptions, OrderSide, OrderType, TradeContext},
1004    /// };
1005    /// use time::macros::datetime;
1006    ///
1007    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1008    /// let oauth = OAuthBuilder::new("your-client-id")
1009    ///     .build(|url| println!("Visit: {url}"))
1010    ///     .await?;
1011    /// let config = Arc::new(Config::from_oauth(oauth));
1012    /// let (ctx, _) = TradeContext::new(config);
1013    ///
1014    /// let resp = ctx
1015    ///     .estimate_max_purchase_quantity(EstimateMaxPurchaseQuantityOptions::new(
1016    ///         "700.HK",
1017    ///         OrderType::LO,
1018    ///         OrderSide::Buy,
1019    ///     ))
1020    ///     .await?;
1021    /// println!("{:?}", resp);
1022    /// # Ok::<_, Box<dyn std::error::Error>>(())
1023    /// # });
1024    /// ```
1025    pub async fn estimate_max_purchase_quantity(
1026        &self,
1027        opts: EstimateMaxPurchaseQuantityOptions,
1028    ) -> Result<EstimateMaxPurchaseQuantityResponse> {
1029        Ok(self
1030            .0
1031            .http_cli
1032            .request(Method::GET, "/v1/trade/estimate/buy_limit")
1033            .query_params(opts)
1034            .response::<Json<EstimateMaxPurchaseQuantityResponse>>()
1035            .send()
1036            .with_subscriber(self.0.log_subscriber.clone())
1037            .await?
1038            .0)
1039    }
1040
1041    // ── US-market APIs
1042    // ────────────────────────────────────────────────────────
1043
1044    /// Query the paginated US order list.
1045    ///
1046    /// Path: `POST /v1/us/orders/query`
1047    ///
1048    /// US token required.
1049    pub async fn us_query_orders(&self, opts: GetUSHistoryOrders) -> Result<QueryUSOrdersResponse> {
1050        use std::time::{SystemTime, UNIX_EPOCH};
1051
1052        let now = SystemTime::now()
1053            .duration_since(UNIX_EPOCH)
1054            .unwrap_or_default()
1055            .as_secs() as i64;
1056
1057        let action = match opts.side {
1058            OrderSide::Buy => 1,
1059            OrderSide::Sell => 2,
1060            _ => 0,
1061        };
1062
1063        let symbols = opts
1064            .symbol
1065            .as_deref()
1066            .filter(|s| !s.is_empty())
1067            .map(|s| vec![s.to_string()])
1068            .unwrap_or_default();
1069
1070        let start_at = if opts.start_at == 0 {
1071            (now - 90 * 24 * 3600) as f64
1072        } else {
1073            opts.start_at as f64
1074        };
1075        let end_at = if opts.end_at == 0 {
1076            now as f64
1077        } else {
1078            opts.end_at as f64
1079        };
1080        let page = if opts.page <= 0 { 1 } else { opts.page };
1081        let limit = if opts.limit <= 0 { 20 } else { opts.limit };
1082
1083        let body = super::types::USQueryOrdersBody {
1084            account_channel: String::new(),
1085            action,
1086            start_at,
1087            end_at,
1088            symbols,
1089            security_types: vec![],
1090            query_type: opts.query_type,
1091            page,
1092            limit,
1093            query_version: now as f64,
1094        };
1095
1096        Ok(self
1097            .0
1098            .http_cli
1099            .request(Method::POST, "/v1/us/orders/query")
1100            .dc_restrict(DcRegion::Us)
1101            .body(Json(body))
1102            .response::<Json<QueryUSOrdersResponse>>()
1103            .send()
1104            .with_subscriber(self.0.log_subscriber.clone())
1105            .await?
1106            .0)
1107    }
1108
1109    /// Get US order detail.
1110    ///
1111    /// Path: `GET /v1/us/orders/{order_id}`
1112    ///
1113    /// US token required.
1114    pub async fn us_order_detail(
1115        &self,
1116        order_id: impl Into<String>,
1117    ) -> Result<USOrderDetailResponse> {
1118        let order_id = order_id.into();
1119        let path = format!("/v1/us/orders/{order_id}");
1120
1121        Ok(self
1122            .0
1123            .http_cli
1124            .request(Method::GET, path.as_str())
1125            .dc_restrict(DcRegion::Us)
1126            .response::<Json<USOrderDetailResponse>>()
1127            .send()
1128            .with_subscriber(self.0.log_subscriber.clone())
1129            .await?
1130            .0)
1131    }
1132
1133    /// Get the full US account asset snapshot (stocks, options, crypto, buying
1134    /// power).
1135    ///
1136    /// Path: `GET /v1/us/assets/overview`
1137    ///
1138    /// US token required.
1139    pub async fn us_asset_overview(&self) -> Result<USAssetOverview> {
1140        Ok(self
1141            .0
1142            .http_cli
1143            .request(Method::GET, "/v1/us/assets/overview")
1144            .dc_restrict(DcRegion::Us)
1145            .response::<Json<USAssetOverview>>()
1146            .send()
1147            .with_subscriber(self.0.log_subscriber.clone())
1148            .await?
1149            .0)
1150    }
1151
1152    /// Get realized profit-and-loss for the US account.
1153    ///
1154    /// `currency`: required, e.g. `"USD"`.
1155    /// `category`: optional filter — `"ALL"`, `"STOCK"`, `"OPTION"`, or
1156    /// `"CRYPTO"`.
1157    ///
1158    /// Path: `GET /v1/us/assets/pl/realized`
1159    ///
1160    /// US token required.
1161    pub async fn us_realized_pl(&self, opts: GetUSRealizedPLOptions) -> Result<USRealizedPL> {
1162        #[derive(Serialize)]
1163        struct Query {
1164            currency: String,
1165            #[serde(skip_serializing_if = "Option::is_none")]
1166            category: Option<String>,
1167        }
1168
1169        let currency = if opts.currency.is_empty() {
1170            "USD".to_string()
1171        } else {
1172            opts.currency
1173        };
1174        let category = if opts.category.is_empty() {
1175            None
1176        } else {
1177            Some(opts.category)
1178        };
1179
1180        Ok(self
1181            .0
1182            .http_cli
1183            .request(Method::GET, "/v1/us/assets/pl/realized")
1184            .dc_restrict(DcRegion::Us)
1185            .query_params(Query { currency, category })
1186            .response::<Json<USRealizedPL>>()
1187            .send()
1188            .with_subscriber(self.0.log_subscriber.clone())
1189            .await?
1190            .0)
1191    }
1192
1193    /// Get cash, buying power and margin status for the US account.
1194    ///
1195    /// `currency`: optional, e.g. `"USD"`.
1196    ///
1197    /// Path: `GET /v1/us/assets/cash-and-buy-power`
1198    ///
1199    /// US token required.
1200    pub async fn us_cash_and_buy_power(&self, currency: Option<&str>) -> Result<USCashAndBuyPower> {
1201        #[derive(Serialize)]
1202        struct Query<'a> {
1203            #[serde(skip_serializing_if = "Option::is_none")]
1204            currency: Option<&'a str>,
1205        }
1206
1207        Ok(self
1208            .0
1209            .http_cli
1210            .request(Method::GET, "/v1/us/assets/cash-and-buy-power")
1211            .dc_restrict(DcRegion::Us)
1212            .query_params(Query { currency })
1213            .response::<Json<USCashAndBuyPower>>()
1214            .send()
1215            .with_subscriber(self.0.log_subscriber.clone())
1216            .await?
1217            .0)
1218    }
1219
1220    /// Get the quantity of a US holding that is available to trade.
1221    ///
1222    /// Path: `GET /v1/us/assets/available-holding`
1223    ///
1224    /// US token required.
1225    pub async fn us_available_holding(
1226        &self,
1227        opts: GetUSAvailableHoldingOptions,
1228    ) -> Result<USAvailableHolding> {
1229        #[derive(Serialize)]
1230        struct Query {
1231            symbol: String,
1232            equity_type: String,
1233            position_side: String,
1234        }
1235
1236        let equity_type = if opts.equity_type.is_empty() {
1237            "STOCK".to_string()
1238        } else {
1239            opts.equity_type
1240        };
1241        let position_side = if opts.position_side.is_empty() {
1242            "LONG".to_string()
1243        } else {
1244            opts.position_side
1245        };
1246
1247        Ok(self
1248            .0
1249            .http_cli
1250            .request(Method::GET, "/v1/us/assets/available-holding")
1251            .dc_restrict(DcRegion::Us)
1252            .query_params(Query {
1253                symbol: opts.symbol,
1254                equity_type,
1255                position_side,
1256            })
1257            .response::<Json<USAvailableHolding>>()
1258            .send()
1259            .with_subscriber(self.0.log_subscriber.clone())
1260            .await?
1261            .0)
1262    }
1263
1264    /// Get the US account transaction history (deposits, withdrawals, trades,
1265    /// corporate actions, transfers and so on), one page at a time.
1266    ///
1267    /// Path: `POST /v1/us/assets/transaction-history`
1268    ///
1269    /// US token required.
1270    pub async fn us_transaction_history(
1271        &self,
1272        opts: GetUSTransactionHistoryOptions,
1273    ) -> Result<USTransactionHistory> {
1274        #[derive(Debug, Serialize)]
1275        struct Body {
1276            start: i64,
1277            end: i64,
1278            page: i32,
1279            size: i32,
1280            #[serde(skip_serializing_if = "Vec::is_empty")]
1281            types: Vec<String>,
1282            #[serde(skip_serializing_if = "String::is_empty")]
1283            currency: String,
1284        }
1285
1286        Ok(self
1287            .0
1288            .http_cli
1289            .request(Method::POST, "/v1/us/assets/transaction-history")
1290            .dc_restrict(DcRegion::Us)
1291            .body(Json(Body {
1292                start: opts.start_at.unix_timestamp(),
1293                end: opts.end_at.unix_timestamp(),
1294                page: if opts.page > 0 { opts.page } else { 1 },
1295                size: if opts.size > 0 { opts.size } else { 20 },
1296                types: opts.types,
1297                currency: opts.currency,
1298            }))
1299            .response::<Json<USTransactionHistory>>()
1300            .send()
1301            .with_subscriber(self.0.log_subscriber.clone())
1302            .await?
1303            .0)
1304    }
1305
1306    /// Get the exchange rates used by the US account.
1307    ///
1308    /// The upstream two-level map is flattened into
1309    /// [`USExchangeRates::exchanges`]; each entry keeps the two upstream map
1310    /// keys as `universal_key` and `spec_key`.
1311    ///
1312    /// Path: `GET /v1/us/assets/exchange-rates`
1313    ///
1314    /// US token required.
1315    pub async fn us_exchange_rates(&self) -> Result<USExchangeRates> {
1316        Ok(self
1317            .0
1318            .http_cli
1319            .request(Method::GET, "/v1/us/assets/exchange-rates")
1320            .dc_restrict(DcRegion::Us)
1321            .response::<Json<USExchangeRates>>()
1322            .send()
1323            .with_subscriber(self.0.log_subscriber.clone())
1324            .await?
1325            .0)
1326    }
1327}
1328
1329#[cfg(test)]
1330mod dc_restrict_tests {
1331    use longport_httpcli::HttpClientError;
1332    use time::macros::datetime;
1333
1334    use super::*;
1335    use crate::Error;
1336
1337    fn us_trade_context() -> TradeContext {
1338        let config = Arc::new(Config::from_apikey("us_app_key", "app_secret", "us_token"));
1339        TradeContext::new(config).0
1340    }
1341
1342    #[track_caller]
1343    fn assert_ap_restricted<T>(res: Result<T>, path: &str)
1344    where
1345        T: std::fmt::Debug,
1346    {
1347        match res {
1348            Err(Error::HttpClient(HttpClientError::DcRegionRestricted {
1349                path: p,
1350                required,
1351                current,
1352            })) => {
1353                assert_eq!(p, path, "restricted path mismatch");
1354                assert_eq!(required, DcRegion::Ap, "expected AP-only restriction");
1355                assert_eq!(current, DcRegion::Us, "expected US session region");
1356            }
1357            other => panic!("expected DcRegionRestricted for {path}, got {other:?}"),
1358        }
1359    }
1360
1361    /// AP-only asset/risk/order endpoints fail fast for a US (`us_`) token
1362    /// instead of sending a request the US data center rejects.
1363    #[tokio::test(flavor = "multi_thread")]
1364    async fn ap_only_endpoints_reject_us_token() {
1365        let ctx = us_trade_context();
1366
1367        assert_ap_restricted(ctx.account_balance(None).await, "/v1/asset/account");
1368        assert_ap_restricted(
1369            ctx.cash_flow(GetCashFlowOptions::new(
1370                datetime!(2026-01-01 0:00 UTC),
1371                datetime!(2026-01-02 0:00 UTC),
1372            ))
1373            .await,
1374            "/v1/asset/cashflow",
1375        );
1376        assert_ap_restricted(ctx.fund_positions(None).await, "/v1/asset/fund");
1377        assert_ap_restricted(ctx.stock_positions(None).await, "/v1/asset/stock");
1378        assert_ap_restricted(ctx.margin_ratio("700.HK").await, "/v1/risk/margin-ratio");
1379        assert_ap_restricted(ctx.order_detail("1").await, "/v1/trade/order");
1380        // all_executions is temporarily disabled
1381    }
1382}
1383
1384#[cfg(test)]
1385mod symbol_normalization_tests {
1386    use time::macros::datetime;
1387
1388    use super::*;
1389    use crate::trade::{
1390        GetCashFlowOptions, GetHistoryExecutionsOptions, GetHistoryOrdersOptions,
1391        GetStockPositionsOptions, GetTodayExecutionsOptions, GetTodayOrdersOptions, OrderSide,
1392        OrderType, SubmitMultiLegOrderLeg, SubmitOrderOptions, TimeInForceType,
1393    };
1394
1395    fn query(value: &impl Serialize) -> String {
1396        serde_json::to_string(&serde_json::to_value(value).unwrap()).unwrap()
1397    }
1398
1399    /// `/v1/asset/stock?symbol=00700.HK` answers `200` with **no** positions
1400    /// rather than an error, so a padded HK symbol has to be canonicalized
1401    /// before it leaves the SDK. Checked against the gateway on 2026-11-18:
1402    /// `700.HK` returned the position, `00700.HK` returned none.
1403    #[test]
1404    fn stock_positions_strips_hk_padding() {
1405        let opts = GetStockPositionsOptions::new().symbols(["00700.HK", "AAPL.US", "000001.SZ"]);
1406        let q = query(&opts);
1407        assert!(q.contains("700.HK"), "{q}");
1408        assert!(!q.contains("00700.HK"), "{q}");
1409        // Every other market keeps its symbol verbatim.
1410        assert!(q.contains("AAPL.US"), "{q}");
1411        assert!(q.contains("000001.SZ"), "{q}");
1412    }
1413
1414    #[test]
1415    fn every_symbol_filter_is_normalized() {
1416        assert!(query(&GetHistoryOrdersOptions::new().symbol("00700.HK")).contains("\"700.HK\""));
1417        assert!(query(&GetTodayOrdersOptions::new().symbol("00700.HK")).contains("\"700.HK\""));
1418        assert!(
1419            query(&GetHistoryExecutionsOptions::new().symbol("00700.HK")).contains("\"700.HK\"")
1420        );
1421        assert!(query(&GetTodayExecutionsOptions::new().symbol("00700.HK")).contains("\"700.HK\""));
1422        assert!(
1423            query(
1424                &GetCashFlowOptions::new(
1425                    datetime!(2026-01-01 0:00 UTC),
1426                    datetime!(2026-01-31 0:00 UTC)
1427                )
1428                .symbol("00700.HK")
1429            )
1430            .contains("\"700.HK\"")
1431        );
1432    }
1433
1434    #[test]
1435    fn submit_order_normalizes_the_symbol() {
1436        let opts = SubmitOrderOptions::new(
1437            "00700.HK",
1438            OrderType::LO,
1439            OrderSide::Buy,
1440            decimal!(100i32),
1441            TimeInForceType::Day,
1442        );
1443        let body = serde_json::to_value(&opts).unwrap();
1444        assert_eq!(body["symbol"], "700.HK");
1445    }
1446
1447    #[test]
1448    fn submit_multileg_normalizes_leg_symbols() {
1449        let leg = SubmitMultiLegOrderLeg::new("00700.HK", decimal!(1i32));
1450        assert_eq!(serde_json::to_value(&leg).unwrap()["symbol"], "700.HK");
1451        let leg = SubmitMultiLegOrderLeg::new("QQQ260731C764000.US", decimal!(1i32));
1452        assert_eq!(
1453            serde_json::to_value(&leg).unwrap()["symbol"],
1454            "QQQ260731C764000.US"
1455        );
1456    }
1457}