longport/quote/context.rs
1use std::{
2 str::FromStr,
3 sync::{Arc, RwLock},
4 time::Duration,
5};
6
7use longport_httpcli::{DcRegion, HttpClient, Json, Method};
8use longport_proto::quote;
9use longport_wscli::WsClientError;
10use rust_decimal::Decimal;
11use serde::{Deserialize, Serialize, de::DeserializeOwned};
12use time::{Date, PrimitiveDateTime};
13use tokio::sync::{mpsc, oneshot};
14use tracing::{Subscriber, dispatcher, instrument::WithSubscriber};
15
16use crate::{
17 Config, Error, Language, Market, QuoteTransport, Result,
18 quote::{
19 AdjustType, CalcIndex, Candlestick, CapitalDistributionResponse, CapitalFlowLine,
20 FilingItem, HistoryMarketTemperatureResponse, IntradayLine, IssuerInfo, MarketTemperature,
21 MarketTradingDays, MarketTradingSession, OptionChainContract, OptionDirection,
22 OptionExpiryCycleType, OptionQuote, OptionStandardAttr, OptionVolumeDaily,
23 OptionVolumeDailyStat, OptionVolumeStats, ParticipantInfo, Period, PushEvent,
24 QuotePackageDetail, RealtimeQuote, RequestCreateWatchlistGroup,
25 RequestUpdateWatchlistGroup, Security, SecurityBrokers, SecurityCalcIndex, SecurityDepth,
26 SecurityListCategory, SecurityQuote, SecurityStaticInfo, ShortPositionsItem,
27 ShortPositionsResponse, ShortTradesItem, ShortTradesResponse, Subscription, Trade,
28 TradeSessions, WarrantInfo, WarrantQuote, WarrantType, WatchlistGroup,
29 cache::{Cache, CacheWithKey},
30 cmd_code,
31 core::{Command, Core, UserProfile},
32 http_json, overnight,
33 sub_flags::SubFlags,
34 types::{
35 FilterWarrantExpiryDate, FilterWarrantInOutBoundsType, PinnedMode,
36 SecuritiesUpdateMode, SortOrderType, WarrantSortBy, WarrantStatus,
37 },
38 utils::{format_date, parse_date},
39 },
40 serde_utils,
41 types::normalize_symbol,
42};
43
44const RETRY_COUNT: usize = 3;
45const PARTICIPANT_INFO_CACHE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
46
47fn history_offset_request(
48 symbol: String,
49 period: Period,
50 adjust_type: AdjustType,
51 forward: bool,
52 time: Option<PrimitiveDateTime>,
53 count: usize,
54 trade_sessions: TradeSessions,
55) -> quote::SecurityHistoryCandlestickRequest {
56 quote::SecurityHistoryCandlestickRequest {
57 symbol,
58 period: period.into(),
59 adjust_type: adjust_type.into(),
60 query_type: quote::HistoryCandlestickQueryType::QueryByOffset.into(),
61 offset_request: Some(quote::security_history_candlestick_request::OffsetQuery {
62 direction: if forward {
63 quote::Direction::Forward
64 } else {
65 quote::Direction::Backward
66 }
67 .into(),
68 date: time
69 .map(|time| {
70 format!(
71 "{:04}{:02}{:02}",
72 time.year(),
73 time.month() as u8,
74 time.day()
75 )
76 })
77 .unwrap_or_default(),
78 minute: time
79 .map(|time| format!("{:02}{:02}", time.hour(), time.minute()))
80 .unwrap_or_default(),
81 count: count as i32,
82 }),
83 date_request: None,
84 trade_session: trade_sessions as i32,
85 }
86}
87
88/// Convert a Unix-seconds string (or integer string) to an RFC 3339 timestamp.
89/// If parsing fails, the original string is returned unchanged.
90fn unix_secs_to_rfc3339(s: &str) -> String {
91 s.parse::<i64>()
92 .ok()
93 .and_then(|ts| time::OffsetDateTime::from_unix_timestamp(ts).ok())
94 .map(|dt| {
95 use time::format_description::well_known::Rfc3339;
96 dt.format(&Rfc3339).unwrap_or_default()
97 })
98 .unwrap_or_else(|| s.to_string())
99}
100const ISSUER_INFO_CACHE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
101const OPTION_CHAIN_EXPIRY_DATE_LIST_CACHE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
102const TRADING_SESSION_CACHE_TIMEOUT: Duration = Duration::from_secs(60 * 60 * 2);
103
104struct InnerQuoteContext {
105 language: Language,
106 quote_transport: QuoteTransport,
107 enable_overnight: bool,
108 http_cli: HttpClient,
109 command_tx: mpsc::UnboundedSender<Command>,
110 /// Kept alive only so the background `Core::run` task can observe the
111 /// context being dropped (via this channel closing) and stop reconnecting.
112 _shutdown_tx: mpsc::UnboundedSender<()>,
113 cache_participants: Cache<Vec<ParticipantInfo>>,
114 cache_issuers: Cache<Vec<IssuerInfo>>,
115 cache_option_chain_expiry_date_list: CacheWithKey<String, Vec<Date>>,
116 cache_trading_session: Cache<Vec<MarketTradingSession>>,
117 user_profile: Arc<RwLock<Option<UserProfile>>>,
118 log_subscriber: Arc<dyn Subscriber + Send + Sync>,
119}
120
121impl Drop for InnerQuoteContext {
122 fn drop(&mut self) {
123 dispatcher::with_default(&self.log_subscriber.clone().into(), || {
124 tracing::info!("quote context dropped");
125 });
126 }
127}
128
129/// Quote context
130#[derive(Clone)]
131pub struct QuoteContext(Arc<InnerQuoteContext>);
132
133impl QuoteContext {
134 /// Create a `QuoteContext`
135 pub fn new(config: Arc<Config>) -> (Self, mpsc::UnboundedReceiver<PushEvent>) {
136 let log_subscriber = config.create_log_subscriber("quote");
137
138 dispatcher::with_default(&log_subscriber.clone().into(), || {
139 tracing::info!(
140 language = ?config.language,
141 enable_overnight = ?config.enable_overnight,
142 push_candlestick_mode = ?config.push_candlestick_mode,
143 enable_print_quote_packages = ?config.enable_print_quote_packages,
144 quote_transport = ?config.quote_transport,
145 "creating quote context"
146 );
147 });
148
149 let language = config.language;
150 let quote_transport = config.quote_transport;
151 let enable_overnight = config.enable_overnight.unwrap_or_default();
152 let http_cli = config.create_http_client();
153 let (command_tx, command_rx) = mpsc::unbounded_channel();
154 let (push_tx, push_rx) = mpsc::unbounded_channel();
155 let (shutdown_tx, shutdown_rx) = mpsc::unbounded_channel();
156 let user_profile = Arc::new(RwLock::new(None::<UserProfile>));
157 let core = Core::new(config, command_rx, push_tx, user_profile.clone());
158 crate::runtime::RUNTIME.handle().spawn(
159 core.run(shutdown_rx)
160 .with_subscriber(log_subscriber.clone()),
161 );
162
163 dispatcher::with_default(&log_subscriber.clone().into(), || {
164 tracing::info!("quote context created");
165 });
166
167 (
168 QuoteContext(Arc::new(InnerQuoteContext {
169 language,
170 quote_transport,
171 enable_overnight,
172 http_cli,
173 command_tx,
174 _shutdown_tx: shutdown_tx,
175 cache_participants: Cache::new(PARTICIPANT_INFO_CACHE_TIMEOUT),
176 cache_issuers: Cache::new(ISSUER_INFO_CACHE_TIMEOUT),
177 cache_option_chain_expiry_date_list: CacheWithKey::new(
178 OPTION_CHAIN_EXPIRY_DATE_LIST_CACHE_TIMEOUT,
179 ),
180 cache_trading_session: Cache::new(TRADING_SESSION_CACHE_TIMEOUT),
181 user_profile,
182 log_subscriber,
183 })),
184 push_rx,
185 )
186 }
187
188 /// Returns the log subscriber
189 #[inline]
190 pub fn log_subscriber(&self) -> Arc<dyn Subscriber + Send + Sync> {
191 self.0.log_subscriber.clone()
192 }
193
194 async fn ensure_user_profile(&self) -> Result<()> {
195 if self.0.user_profile.read().unwrap().is_some() {
196 return Ok(());
197 }
198 let (reply_tx, reply_rx) = oneshot::channel();
199 self.0
200 .command_tx
201 .send(Command::EnsureConnected { reply_tx })
202 .map_err(|_| WsClientError::ClientClosed)?;
203 reply_rx.await.map_err(|_| WsClientError::ClientClosed)?
204 }
205
206 /// Returns the member ID
207 pub async fn member_id(&self) -> Result<i64> {
208 self.ensure_user_profile().await?;
209 Ok(self
210 .0
211 .user_profile
212 .read()
213 .unwrap()
214 .as_ref()
215 .unwrap()
216 .member_id)
217 }
218
219 /// Returns the quote level
220 pub async fn quote_level(&self) -> Result<String> {
221 self.ensure_user_profile().await?;
222 Ok(self
223 .0
224 .user_profile
225 .read()
226 .unwrap()
227 .as_ref()
228 .unwrap()
229 .quote_level
230 .clone())
231 }
232
233 /// Returns the quote package details
234 pub async fn quote_package_details(&self) -> Result<Vec<QuotePackageDetail>> {
235 self.ensure_user_profile().await?;
236 Ok(self
237 .0
238 .user_profile
239 .read()
240 .unwrap()
241 .as_ref()
242 .unwrap()
243 .quote_package_details
244 .clone())
245 }
246
247 /// Send a raw request
248 async fn request_raw(&self, command_code: u8, body: Vec<u8>) -> Result<Vec<u8>> {
249 for _ in 0..RETRY_COUNT {
250 let (reply_tx, reply_rx) = oneshot::channel();
251 self.0
252 .command_tx
253 .send(Command::Request {
254 command_code,
255 body: body.clone(),
256 reply_tx,
257 })
258 .map_err(|_| WsClientError::ClientClosed)?;
259 let res = reply_rx.await.map_err(|_| WsClientError::ClientClosed)?;
260
261 match res {
262 Ok(resp) => return Ok(resp),
263 Err(Error::WsClient(WsClientError::Cancelled)) => {}
264 Err(err) => return Err(err),
265 }
266 }
267
268 Err(Error::WsClient(WsClientError::RequestTimeout))
269 }
270
271 /// Send a request `T` to get a response `R`
272 ///
273 /// With [`QuoteTransport::Http`], a command that has a REST equivalent is
274 /// sent as `POST /quote/*` with the same message as a JSON body, and the
275 /// JSON response is decoded into the same message type, so callers are
276 /// transport-agnostic.
277 async fn request<T, R>(&self, command_code: u8, req: T) -> Result<R>
278 where
279 T: prost::Message + Serialize,
280 R: prost::Message + Default + DeserializeOwned,
281 {
282 if let Some(path) = self.http_path(command_code) {
283 return self.http_request(path, req).await;
284 }
285
286 let resp = self.request_raw(command_code, req.encode_to_vec()).await?;
287 Ok(R::decode(&*resp)?)
288 }
289
290 /// Send a request to get a response `R`
291 async fn request_without_body<R>(&self, command_code: u8) -> Result<R>
292 where
293 R: prost::Message + Default + DeserializeOwned,
294 {
295 if let Some(path) = self.http_path(command_code) {
296 return self
297 .http_request(path, serde_json::Value::Object(Default::default()))
298 .await;
299 }
300
301 let resp = self.request_raw(command_code, vec![]).await?;
302 Ok(R::decode(&*resp)?)
303 }
304
305 /// Whether this context must drop US overnight data to match what the
306 /// WebSocket returns: see [`overnight`].
307 fn aligns_overnight(&self) -> bool {
308 self.0.quote_transport == QuoteTransport::Http && !self.0.enable_overnight
309 }
310
311 /// Convert a candlestick page, dropping overnight candlesticks when
312 /// [`Self::aligns_overnight`], `symbol` is a US equity and the query asked
313 /// for all sessions (the only case that both drops and tops up). Returns
314 /// the candlesticks and how many were dropped.
315 fn convert_candlesticks(
316 &self,
317 symbol: &str,
318 trade_sessions: TradeSessions,
319 resp: quote::SecurityCandlestickResponse,
320 ) -> Result<(Vec<Candlestick>, usize)> {
321 if self.aligns_overnight()
322 && trade_sessions == TradeSessions::All
323 && overnight::is_us_equity_symbol(symbol)
324 {
325 overnight::drop_overnight(resp.candlesticks)
326 } else {
327 Ok((
328 resp.candlesticks
329 .into_iter()
330 .map(TryInto::try_into)
331 .collect::<Result<_>>()?,
332 0,
333 ))
334 }
335 }
336
337 /// Convert a raw candlestick page and, on the HTTP transport, top up a
338 /// capped US window after overnight bars were dropped so it covers the
339 /// same bars as the WebSocket (see [`overnight`]). The top-up pages with
340 /// `POST /quote/history-candlesticks` offset queries; a failure there
341 /// fails the call.
342 #[allow(clippy::too_many_arguments)]
343 async fn align_candlesticks(
344 &self,
345 resp: quote::SecurityCandlestickResponse,
346 symbol: &str,
347 period: Period,
348 adjust_type: AdjustType,
349 trade_sessions: TradeSessions,
350 forward: bool,
351 window: overnight::CandlestickWindow,
352 ) -> Result<Vec<Candlestick>> {
353 let target = overnight::window_target(window, &resp.candlesticks);
354 let cursor = overnight::raw_edge(&resp.candlesticks, forward);
355 let (candlesticks, dropped) = self.convert_candlesticks(symbol, trade_sessions, resp)?;
356 let (Some(target), true) = (target, dropped > 0 && trade_sessions == TradeSessions::All)
357 else {
358 return Ok(candlesticks);
359 };
360 let bound = match window {
361 overnight::CandlestickWindow::DateRange { start } => start,
362 overnight::CandlestickWindow::Count(_) => None,
363 };
364 overnight::refill(
365 forward,
366 candlesticks,
367 cursor,
368 target,
369 bound,
370 |anchor, count| {
371 let request = history_offset_request(
372 symbol.to_string(),
373 period,
374 adjust_type,
375 forward,
376 Some(anchor),
377 count,
378 trade_sessions,
379 );
380 async move {
381 let resp: quote::SecurityCandlestickResponse = self
382 .request(cmd_code::GET_SECURITY_HISTORY_CANDLESTICKS, request)
383 .await?;
384 Ok(resp.candlesticks)
385 }
386 },
387 )
388 .await
389 .map(|(candlesticks, round_limit_hit)| {
390 if round_limit_hit {
391 dispatcher::with_default(&self.0.log_subscriber.clone().into(), || {
392 tracing::warn!(
393 symbol,
394 target,
395 got = candlesticks.len(),
396 "overnight top-up hit its round limit; fewer candlesticks than the WebSocket would return"
397 );
398 });
399 }
400 candlesticks
401 })
402 }
403
404 /// Returns the REST path to use for `command_code`, if the HTTP transport
405 /// is selected and the command has a REST equivalent.
406 fn http_path(&self, command_code: u8) -> Option<&'static str> {
407 match self.0.quote_transport {
408 QuoteTransport::Http => cmd_code::http_path(command_code),
409 QuoteTransport::WebSocket => None,
410 }
411 }
412
413 /// `POST` `body` to `path` and decode the proto-JSON response into `R`.
414 ///
415 /// Absent sub-messages (`Option::None`) are omitted from the body instead
416 /// of being sent as `null`, matching how a proto-JSON client would encode
417 /// them.
418 async fn http_request<B, R>(&self, path: &'static str, body: B) -> Result<R>
419 where
420 B: Serialize,
421 R: DeserializeOwned,
422 {
423 let mut body = serde_json::to_value(body)?;
424 http_json::strip_nulls(&mut body);
425 let Json(value) = self
426 .0
427 .http_cli
428 .request(Method::POST, path)
429 .body(Json(body))
430 .response::<Json<serde_json::Value>>()
431 .send()
432 .with_subscriber(self.0.log_subscriber.clone())
433 .await?;
434 Ok(http_json::from_value(value)?)
435 }
436
437 /// Subscribe
438 ///
439 /// Reference: <https://open.longportapp.com/en/docs/quote/subscribe/subscribe>
440 ///
441 /// # Examples
442 ///
443 /// ```no_run
444 /// use std::sync::Arc;
445 ///
446 /// use longport::{
447 /// Config,
448 /// oauth::OAuthBuilder,
449 /// quote::{QuoteContext, SubFlags},
450 /// };
451 ///
452 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
453 /// let oauth = OAuthBuilder::new("your-client-id")
454 /// .build(|url| println!("Visit: {url}"))
455 /// .await?;
456 /// let config = Arc::new(Config::from_oauth(oauth));
457 /// let (ctx, mut receiver) = QuoteContext::new(config);
458 ///
459 /// ctx.subscribe(["700.HK", "AAPL.US"], SubFlags::QUOTE)
460 /// .await?;
461 /// while let Some(msg) = receiver.recv().await {
462 /// println!("{:?}", msg);
463 /// }
464 /// # Ok::<_, Box<dyn std::error::Error>>(())
465 /// # });
466 /// ```
467 pub async fn subscribe<I, T>(&self, symbols: I, sub_types: impl Into<SubFlags>) -> Result<()>
468 where
469 I: IntoIterator<Item = T>,
470 T: AsRef<str>,
471 {
472 let (reply_tx, reply_rx) = oneshot::channel();
473 self.0
474 .command_tx
475 .send(Command::Subscribe {
476 symbols: symbols
477 .into_iter()
478 .map(|symbol| normalize_symbol(symbol.as_ref()).to_string())
479 .collect(),
480 sub_types: sub_types.into(),
481 reply_tx,
482 })
483 .map_err(|_| WsClientError::ClientClosed)?;
484 reply_rx.await.map_err(|_| WsClientError::ClientClosed)?
485 }
486
487 /// Unsubscribe
488 ///
489 /// Reference: <https://open.longportapp.com/en/docs/quote/subscribe/unsubscribe>
490 ///
491 /// # Examples
492 ///
493 /// ```no_run
494 /// use std::sync::Arc;
495 ///
496 /// use longport::{
497 /// Config,
498 /// oauth::OAuthBuilder,
499 /// quote::{QuoteContext, SubFlags},
500 /// };
501 ///
502 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
503 /// let oauth = OAuthBuilder::new("your-client-id")
504 /// .build(|url| println!("Visit: {url}"))
505 /// .await?;
506 /// let config = Arc::new(Config::from_oauth(oauth));
507 /// let (ctx, _) = QuoteContext::new(config);
508 ///
509 /// ctx.subscribe(["700.HK", "AAPL.US"], SubFlags::QUOTE)
510 /// .await?;
511 /// ctx.unsubscribe(["AAPL.US"], SubFlags::QUOTE).await?;
512 /// # Ok::<_, Box<dyn std::error::Error>>(())
513 /// # });
514 /// ```
515 pub async fn unsubscribe<I, T>(&self, symbols: I, sub_types: impl Into<SubFlags>) -> Result<()>
516 where
517 I: IntoIterator<Item = T>,
518 T: AsRef<str>,
519 {
520 let (reply_tx, reply_rx) = oneshot::channel();
521 self.0
522 .command_tx
523 .send(Command::Unsubscribe {
524 symbols: symbols
525 .into_iter()
526 .map(|symbol| normalize_symbol(symbol.as_ref()).to_string())
527 .collect(),
528 sub_types: sub_types.into(),
529 reply_tx,
530 })
531 .map_err(|_| WsClientError::ClientClosed)?;
532 reply_rx.await.map_err(|_| WsClientError::ClientClosed)?
533 }
534
535 /// Subscribe security candlesticks
536 ///
537 /// # Examples
538 ///
539 /// ```no_run
540 /// use std::sync::Arc;
541 ///
542 /// use longport::{
543 /// Config,
544 /// oauth::OAuthBuilder,
545 /// quote::{Period, QuoteContext, TradeSessions},
546 /// };
547 ///
548 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
549 /// let oauth = OAuthBuilder::new("your-client-id")
550 /// .build(|url| println!("Visit: {url}"))
551 /// .await?;
552 /// let config = Arc::new(Config::from_oauth(oauth));
553 /// let (ctx, mut receiver) = QuoteContext::new(config);
554 ///
555 /// ctx.subscribe_candlesticks("AAPL.US", Period::OneMinute, TradeSessions::Intraday)
556 /// .await?;
557 /// while let Some(msg) = receiver.recv().await {
558 /// println!("{:?}", msg);
559 /// }
560 /// # Ok::<_, Box<dyn std::error::Error>>(())
561 /// # });
562 /// ```
563 pub async fn subscribe_candlesticks<T>(
564 &self,
565 symbol: T,
566 period: Period,
567 trade_sessions: TradeSessions,
568 ) -> Result<Vec<Candlestick>>
569 where
570 T: AsRef<str>,
571 {
572 let (reply_tx, reply_rx) = oneshot::channel();
573 self.0
574 .command_tx
575 .send(Command::SubscribeCandlesticks {
576 symbol: normalize_symbol(symbol.as_ref()).into(),
577 period,
578 trade_sessions,
579 reply_tx,
580 })
581 .map_err(|_| WsClientError::ClientClosed)?;
582 reply_rx.await.map_err(|_| WsClientError::ClientClosed)?
583 }
584
585 /// Unsubscribe security candlesticks
586 pub async fn unsubscribe_candlesticks<T>(&self, symbol: T, period: Period) -> Result<()>
587 where
588 T: AsRef<str>,
589 {
590 let (reply_tx, reply_rx) = oneshot::channel();
591 self.0
592 .command_tx
593 .send(Command::UnsubscribeCandlesticks {
594 symbol: normalize_symbol(symbol.as_ref()).into(),
595 period,
596 reply_tx,
597 })
598 .map_err(|_| WsClientError::ClientClosed)?;
599 reply_rx.await.map_err(|_| WsClientError::ClientClosed)?
600 }
601
602 /// Get subscription information
603 ///
604 /// # Examples
605 ///
606 /// ```no_run
607 /// use std::sync::Arc;
608 ///
609 /// use longport::{
610 /// Config,
611 /// oauth::OAuthBuilder,
612 /// quote::{QuoteContext, SubFlags},
613 /// };
614 ///
615 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
616 /// let oauth = OAuthBuilder::new("your-client-id")
617 /// .build(|url| println!("Visit: {url}"))
618 /// .await?;
619 /// let config = Arc::new(Config::from_oauth(oauth));
620 /// let (ctx, _) = QuoteContext::new(config);
621 ///
622 /// ctx.subscribe(["700.HK", "AAPL.US"], SubFlags::QUOTE)
623 /// .await?;
624 /// let resp = ctx.subscriptions().await?;
625 /// println!("{:?}", resp);
626 /// # Ok::<_, Box<dyn std::error::Error>>(())
627 /// # });
628 /// ```
629 pub async fn subscriptions(&self) -> Result<Vec<Subscription>> {
630 let (reply_tx, reply_rx) = oneshot::channel();
631 self.0
632 .command_tx
633 .send(Command::Subscriptions { reply_tx })
634 .map_err(|_| WsClientError::ClientClosed)?;
635 Ok(reply_rx.await.map_err(|_| WsClientError::ClientClosed)?)
636 }
637
638 /// Get basic information of securities
639 ///
640 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/static>
641 ///
642 /// # Examples
643 ///
644 /// ```no_run
645 /// use std::sync::Arc;
646 ///
647 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
648 ///
649 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
650 /// let oauth = OAuthBuilder::new("your-client-id")
651 /// .build(|url| println!("Visit: {url}"))
652 /// .await?;
653 /// let config = Arc::new(Config::from_oauth(oauth));
654 /// let (ctx, _) = QuoteContext::new(config);
655 ///
656 /// let resp = ctx
657 /// .static_info(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
658 /// .await?;
659 /// println!("{:?}", resp);
660 /// # Ok::<_, Box<dyn std::error::Error>>(())
661 /// # });
662 /// ```
663 pub async fn static_info<I, T>(&self, symbols: I) -> Result<Vec<SecurityStaticInfo>>
664 where
665 I: IntoIterator<Item = T>,
666 T: Into<String>,
667 {
668 let resp: quote::SecurityStaticInfoResponse = self
669 .request(
670 cmd_code::GET_BASIC_INFO,
671 quote::MultiSecurityRequest {
672 symbol: symbols.into_iter().map(Into::into).collect(),
673 },
674 )
675 .await?;
676 resp.secu_static_info
677 .into_iter()
678 .map(TryInto::try_into)
679 .collect()
680 }
681
682 /// Get quote of securities
683 ///
684 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/quote>
685 ///
686 /// # Examples
687 ///
688 /// ```no_run
689 /// use std::sync::Arc;
690 ///
691 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
692 ///
693 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
694 /// let oauth = OAuthBuilder::new("your-client-id")
695 /// .build(|url| println!("Visit: {url}"))
696 /// .await?;
697 /// let config = Arc::new(Config::from_oauth(oauth));
698 /// let (ctx, _) = QuoteContext::new(config);
699 ///
700 /// let resp = ctx
701 /// .quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
702 /// .await?;
703 /// println!("{:?}", resp);
704 /// # Ok::<_, Box<dyn std::error::Error>>(())
705 /// # });
706 /// ```
707 pub async fn quote<I, T>(&self, symbols: I) -> Result<Vec<SecurityQuote>>
708 where
709 I: IntoIterator<Item = T>,
710 T: Into<String>,
711 {
712 let resp: quote::SecurityQuoteResponse = self
713 .request(
714 cmd_code::GET_REALTIME_QUOTE,
715 quote::MultiSecurityRequest {
716 symbol: symbols.into_iter().map(Into::into).collect(),
717 },
718 )
719 .await?;
720 resp.secu_quote
721 .into_iter()
722 .map(|mut quote| {
723 // See `overnight`: HTTP always returns overnight quotes.
724 if self.aligns_overnight() && overnight::is_us_equity_symbol("e.symbol) {
725 quote.over_night_quote = None;
726 }
727 quote.try_into()
728 })
729 .collect()
730 }
731
732 /// Get quote of option securities
733 ///
734 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/option-quote>
735 ///
736 /// # Examples
737 ///
738 /// ```no_run
739 /// use std::sync::Arc;
740 ///
741 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
742 ///
743 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
744 /// let oauth = OAuthBuilder::new("your-client-id")
745 /// .build(|url| println!("Visit: {url}"))
746 /// .await?;
747 /// let config = Arc::new(Config::from_oauth(oauth));
748 /// let (ctx, _) = QuoteContext::new(config);
749 ///
750 /// let resp = ctx.option_quote(["AAPL230317P160000.US"]).await?;
751 /// println!("{:?}", resp);
752 /// # Ok::<_, Box<dyn std::error::Error>>(())
753 /// # });
754 /// ```
755 pub async fn option_quote<I, T>(&self, symbols: I) -> Result<Vec<OptionQuote>>
756 where
757 I: IntoIterator<Item = T>,
758 T: Into<String>,
759 {
760 let resp: quote::OptionQuoteResponse = self
761 .request(
762 cmd_code::GET_REALTIME_OPTION_QUOTE,
763 quote::MultiSecurityRequest {
764 symbol: symbols.into_iter().map(Into::into).collect(),
765 },
766 )
767 .await?;
768 resp.secu_quote.into_iter().map(TryInto::try_into).collect()
769 }
770
771 /// Get quote of warrant securities
772 ///
773 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/warrant-quote>
774 ///
775 /// # Examples
776 ///
777 /// ```no_run
778 /// use std::sync::Arc;
779 ///
780 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
781 ///
782 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
783 /// let oauth = OAuthBuilder::new("your-client-id")
784 /// .build(|url| println!("Visit: {url}"))
785 /// .await?;
786 /// let config = Arc::new(Config::from_oauth(oauth));
787 /// let (ctx, _) = QuoteContext::new(config);
788 ///
789 /// let resp = ctx.warrant_quote(["21125.HK"]).await?;
790 /// println!("{:?}", resp);
791 /// # Ok::<_, Box<dyn std::error::Error>>(())
792 /// # });
793 /// ```
794 pub async fn warrant_quote<I, T>(&self, symbols: I) -> Result<Vec<WarrantQuote>>
795 where
796 I: IntoIterator<Item = T>,
797 T: Into<String>,
798 {
799 let resp: quote::WarrantQuoteResponse = self
800 .request(
801 cmd_code::GET_REALTIME_WARRANT_QUOTE,
802 quote::MultiSecurityRequest {
803 symbol: symbols.into_iter().map(Into::into).collect(),
804 },
805 )
806 .await?;
807 resp.secu_quote.into_iter().map(TryInto::try_into).collect()
808 }
809
810 /// Get security depth
811 ///
812 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/depth>
813 ///
814 /// # Examples
815 ///
816 /// ```no_run
817 /// use std::sync::Arc;
818 ///
819 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
820 ///
821 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
822 /// let oauth = OAuthBuilder::new("your-client-id")
823 /// .build(|url| println!("Visit: {url}"))
824 /// .await?;
825 /// let config = Arc::new(Config::from_oauth(oauth));
826 /// let (ctx, _) = QuoteContext::new(config);
827 ///
828 /// let resp = ctx.depth("700.HK").await?;
829 /// println!("{:?}", resp);
830 /// # Ok::<_, Box<dyn std::error::Error>>(())
831 /// # });
832 /// ```
833 pub async fn depth(&self, symbol: impl Into<String>) -> Result<SecurityDepth> {
834 let resp: quote::SecurityDepthResponse = self
835 .request(
836 cmd_code::GET_SECURITY_DEPTH,
837 quote::SecurityRequest {
838 symbol: symbol.into(),
839 },
840 )
841 .await?;
842 Ok(SecurityDepth {
843 asks: resp
844 .ask
845 .into_iter()
846 .map(TryInto::try_into)
847 .collect::<Result<Vec<_>>>()?,
848 bids: resp
849 .bid
850 .into_iter()
851 .map(TryInto::try_into)
852 .collect::<Result<Vec<_>>>()?,
853 })
854 }
855
856 /// Get security brokers
857 ///
858 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/brokers>
859 ///
860 /// # Examples
861 ///
862 /// ```no_run
863 /// use std::sync::Arc;
864 ///
865 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
866 ///
867 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
868 /// let oauth = OAuthBuilder::new("your-client-id")
869 /// .build(|url| println!("Visit: {url}"))
870 /// .await?;
871 /// let config = Arc::new(Config::from_oauth(oauth));
872 /// let (ctx, _) = QuoteContext::new(config);
873 ///
874 /// let resp = ctx.brokers("700.HK").await?;
875 /// println!("{:?}", resp);
876 /// # Ok::<_, Box<dyn std::error::Error>>(())
877 /// # });
878 /// ```
879 pub async fn brokers(&self, symbol: impl Into<String>) -> Result<SecurityBrokers> {
880 // Broker queue is served only by the AP data center; short-circuit a
881 // non-AP session with the same unified error the HTTP path returns.
882 let current = self.0.http_cli.dc_region().await;
883 if !current.allows(longport_httpcli::DcRegion::Ap) {
884 return Err(longport_httpcli::HttpClientError::DcRegionRestricted {
885 path: "quote/brokers".to_string(),
886 required: longport_httpcli::DcRegion::Ap,
887 current,
888 }
889 .into());
890 }
891 let resp: quote::SecurityBrokersResponse = self
892 .request(
893 cmd_code::GET_SECURITY_BROKERS,
894 quote::SecurityRequest {
895 symbol: symbol.into(),
896 },
897 )
898 .await?;
899 Ok(SecurityBrokers {
900 ask_brokers: resp.ask_brokers.into_iter().map(Into::into).collect(),
901 bid_brokers: resp.bid_brokers.into_iter().map(Into::into).collect(),
902 })
903 }
904
905 /// Get participants
906 ///
907 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/broker-ids>
908 ///
909 /// # Examples
910 ///
911 /// ```no_run
912 /// use std::sync::Arc;
913 ///
914 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
915 ///
916 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
917 /// let oauth = OAuthBuilder::new("your-client-id")
918 /// .build(|url| println!("Visit: {url}"))
919 /// .await?;
920 /// let config = Arc::new(Config::from_oauth(oauth));
921 /// let (ctx, _) = QuoteContext::new(config);
922 ///
923 /// let resp = ctx.participants().await?;
924 /// println!("{:?}", resp);
925 /// # Ok::<_, Box<dyn std::error::Error>>(())
926 /// # });
927 /// ```
928 pub async fn participants(&self) -> Result<Vec<ParticipantInfo>> {
929 self.0
930 .cache_participants
931 .get_or_update(|| async {
932 let resp = self
933 .request_without_body::<quote::ParticipantBrokerIdsResponse>(
934 cmd_code::GET_BROKER_IDS,
935 )
936 .await?;
937
938 Ok(resp
939 .participant_broker_numbers
940 .into_iter()
941 .map(Into::into)
942 .collect())
943 })
944 .await
945 }
946
947 /// Get security trades
948 ///
949 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/trade>
950 ///
951 /// # Examples
952 ///
953 /// ```no_run
954 /// use std::sync::Arc;
955 ///
956 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
957 ///
958 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
959 /// let oauth = OAuthBuilder::new("your-client-id")
960 /// .build(|url| println!("Visit: {url}"))
961 /// .await?;
962 /// let config = Arc::new(Config::from_oauth(oauth));
963 /// let (ctx, _) = QuoteContext::new(config);
964 ///
965 /// let resp = ctx.trades("700.HK", 10).await?;
966 /// println!("{:?}", resp);
967 /// # Ok::<_, Box<dyn std::error::Error>>(())
968 /// # });
969 /// ```
970 pub async fn trades(&self, symbol: impl Into<String>, count: usize) -> Result<Vec<Trade>> {
971 let resp: quote::SecurityTradeResponse = self
972 .request(
973 cmd_code::GET_SECURITY_TRADES,
974 quote::SecurityTradeRequest {
975 symbol: symbol.into(),
976 count: count as i32,
977 },
978 )
979 .await?;
980 let trades = resp
981 .trades
982 .into_iter()
983 .map(TryInto::try_into)
984 .collect::<Result<Vec<_>>>()?;
985 Ok(trades)
986 }
987
988 /// Get security intraday lines
989 ///
990 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/intraday>
991 ///
992 /// # Examples
993 ///
994 /// ```no_run
995 /// use std::sync::Arc;
996 ///
997 /// use longport::{
998 /// Config,
999 /// oauth::OAuthBuilder,
1000 /// quote::{QuoteContext, TradeSessions},
1001 /// };
1002 ///
1003 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1004 /// let oauth = OAuthBuilder::new("your-client-id")
1005 /// .build(|url| println!("Visit: {url}"))
1006 /// .await?;
1007 /// let config = Arc::new(Config::from_oauth(oauth));
1008 /// let (ctx, _) = QuoteContext::new(config);
1009 ///
1010 /// let resp = ctx.intraday("700.HK", TradeSessions::Intraday).await?;
1011 /// println!("{:?}", resp);
1012 /// # Ok::<_, Box<dyn std::error::Error>>(())
1013 /// # });
1014 /// ```
1015 pub async fn intraday(
1016 &self,
1017 symbol: impl Into<String>,
1018 trade_sessions: TradeSessions,
1019 ) -> Result<Vec<IntradayLine>> {
1020 let symbol = symbol.into();
1021 let drop_overnight = self.aligns_overnight() && overnight::is_us_equity_symbol(&symbol);
1022 let resp: quote::SecurityIntradayResponse = self
1023 .request(
1024 cmd_code::GET_SECURITY_INTRADAY,
1025 quote::SecurityIntradayRequest {
1026 symbol,
1027 trade_session: trade_sessions as i32,
1028 },
1029 )
1030 .await?;
1031 let lines = resp
1032 .lines
1033 .into_iter()
1034 .map(TryInto::<IntradayLine>::try_into)
1035 .filter(|line| {
1036 // See `overnight`: HTTP always returns the overnight session.
1037 !drop_overnight
1038 || !matches!(line, Ok(line) if overnight::is_us_overnight(line.timestamp))
1039 })
1040 .collect::<Result<Vec<_>>>()?;
1041 Ok(lines)
1042 }
1043
1044 /// Get security candlesticks
1045 ///
1046 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/candlestick>
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```no_run
1051 /// use std::sync::Arc;
1052 ///
1053 /// use longport::{
1054 /// Config,
1055 /// oauth::OAuthBuilder,
1056 /// quote::{AdjustType, Period, QuoteContext, TradeSessions},
1057 /// };
1058 ///
1059 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1060 /// let oauth = OAuthBuilder::new("your-client-id")
1061 /// .build(|url| println!("Visit: {url}"))
1062 /// .await?;
1063 /// let config = Arc::new(Config::from_oauth(oauth));
1064 /// let (ctx, _) = QuoteContext::new(config);
1065 ///
1066 /// let resp = ctx
1067 /// .candlesticks(
1068 /// "700.HK",
1069 /// Period::Day,
1070 /// 10,
1071 /// AdjustType::NoAdjust,
1072 /// TradeSessions::Intraday,
1073 /// )
1074 /// .await?;
1075 /// println!("{:?}", resp);
1076 /// # Ok::<_, Box<dyn std::error::Error>>(())
1077 /// # });
1078 /// ```
1079 pub async fn candlesticks(
1080 &self,
1081 symbol: impl Into<String>,
1082 period: Period,
1083 count: usize,
1084 adjust_type: AdjustType,
1085 trade_sessions: TradeSessions,
1086 ) -> Result<Vec<Candlestick>> {
1087 let symbol = symbol.into();
1088 let resp: quote::SecurityCandlestickResponse = self
1089 .request(
1090 cmd_code::GET_SECURITY_CANDLESTICKS,
1091 quote::SecurityCandlestickRequest {
1092 symbol: symbol.clone(),
1093 period: period.into(),
1094 count: count as i32,
1095 adjust_type: adjust_type.into(),
1096 trade_session: trade_sessions as i32,
1097 },
1098 )
1099 .await?;
1100 self.align_candlesticks(
1101 resp,
1102 &symbol,
1103 period,
1104 adjust_type,
1105 trade_sessions,
1106 false,
1107 overnight::CandlestickWindow::Count(count),
1108 )
1109 .await
1110 }
1111
1112 /// Get security history candlesticks by offset
1113 #[allow(clippy::too_many_arguments)]
1114 pub async fn history_candlesticks_by_offset(
1115 &self,
1116 symbol: impl Into<String>,
1117 period: Period,
1118 adjust_type: AdjustType,
1119 forward: bool,
1120 time: Option<PrimitiveDateTime>,
1121 count: usize,
1122 trade_sessions: TradeSessions,
1123 ) -> Result<Vec<Candlestick>> {
1124 let symbol = symbol.into();
1125 let resp: quote::SecurityCandlestickResponse = self
1126 .request(
1127 cmd_code::GET_SECURITY_HISTORY_CANDLESTICKS,
1128 history_offset_request(
1129 symbol.clone(),
1130 period,
1131 adjust_type,
1132 forward,
1133 time,
1134 count,
1135 trade_sessions,
1136 ),
1137 )
1138 .await?;
1139 self.align_candlesticks(
1140 resp,
1141 &symbol,
1142 period,
1143 adjust_type,
1144 trade_sessions,
1145 forward,
1146 overnight::CandlestickWindow::Count(count),
1147 )
1148 .await
1149 }
1150
1151 /// Get security history candlesticks by date
1152 pub async fn history_candlesticks_by_date(
1153 &self,
1154 symbol: impl Into<String>,
1155 period: Period,
1156 adjust_type: AdjustType,
1157 start: Option<Date>,
1158 end: Option<Date>,
1159 trade_sessions: TradeSessions,
1160 ) -> Result<Vec<Candlestick>> {
1161 let symbol = symbol.into();
1162 let resp: quote::SecurityCandlestickResponse = self
1163 .request(
1164 cmd_code::GET_SECURITY_HISTORY_CANDLESTICKS,
1165 quote::SecurityHistoryCandlestickRequest {
1166 symbol: symbol.clone(),
1167 period: period.into(),
1168 adjust_type: adjust_type.into(),
1169 query_type: quote::HistoryCandlestickQueryType::QueryByDate.into(),
1170 offset_request: None,
1171 date_request: Some(quote::security_history_candlestick_request::DateQuery {
1172 start_date: start
1173 .map(|date| {
1174 format!(
1175 "{:04}{:02}{:02}",
1176 date.year(),
1177 date.month() as u8,
1178 date.day()
1179 )
1180 })
1181 .unwrap_or_default(),
1182 end_date: end
1183 .map(|date| {
1184 format!(
1185 "{:04}{:02}{:02}",
1186 date.year(),
1187 date.month() as u8,
1188 date.day()
1189 )
1190 })
1191 .unwrap_or_default(),
1192 }),
1193 trade_session: trade_sessions as i32,
1194 },
1195 )
1196 .await?;
1197 self.align_candlesticks(
1198 resp,
1199 &symbol,
1200 period,
1201 adjust_type,
1202 trade_sessions,
1203 false,
1204 overnight::CandlestickWindow::DateRange { start },
1205 )
1206 .await
1207 }
1208
1209 /// Get option chain expiry date list
1210 ///
1211 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/optionchain-date>
1212 ///
1213 /// # Examples
1214 ///
1215 /// ```no_run
1216 /// use std::sync::Arc;
1217 ///
1218 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
1219 ///
1220 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1221 /// let oauth = OAuthBuilder::new("your-client-id")
1222 /// .build(|url| println!("Visit: {url}"))
1223 /// .await?;
1224 /// let config = Arc::new(Config::from_oauth(oauth));
1225 /// let (ctx, _) = QuoteContext::new(config);
1226 ///
1227 /// let resp = ctx.option_chain_expiry_date_list("AAPL.US").await?;
1228 /// println!("{:?}", resp);
1229 /// # Ok::<_, Box<dyn std::error::Error>>(())
1230 /// # });
1231 /// ```
1232 pub async fn option_chain_expiry_date_list(
1233 &self,
1234 symbol: impl Into<String>,
1235 ) -> Result<Vec<Date>> {
1236 self.0
1237 .cache_option_chain_expiry_date_list
1238 .get_or_update(symbol.into(), |symbol| async {
1239 let resp: quote::OptionChainDateListResponse = self
1240 .request(
1241 cmd_code::GET_OPTION_CHAIN_EXPIRY_DATE_LIST,
1242 quote::SecurityRequest { symbol },
1243 )
1244 .await?;
1245 resp.expiry_date
1246 .iter()
1247 .map(|value| {
1248 parse_date(value).map_err(|err| Error::parse_field_error("date", err))
1249 })
1250 .collect::<Result<Vec<_>>>()
1251 })
1252 .await
1253 }
1254
1255 /// Get the option contract list of an underlying security for a given
1256 /// expiry date
1257 ///
1258 /// Every contract is an independent entry: calls and puts are not paired,
1259 /// so a strike price that is listed on one side only yields a single entry.
1260 ///
1261 /// `standard_only` filters out the legacy contracts produced by corporate
1262 /// actions. `true` returns standard contracts only; `false` returns
1263 /// everything, including the contracts carrying
1264 /// [`OptionStandardAttr::Old`].
1265 ///
1266 /// Path: `POST /v1/quote/options/strikes`
1267 ///
1268 /// # Examples
1269 ///
1270 /// ```no_run
1271 /// use std::sync::Arc;
1272 ///
1273 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
1274 /// use time::macros::date;
1275 ///
1276 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1277 /// let oauth = OAuthBuilder::new("your-client-id")
1278 /// .build(|url| println!("Visit: {url}"))
1279 /// .await?;
1280 /// let config = Arc::new(Config::from_oauth(oauth));
1281 /// let (ctx, _) = QuoteContext::new(config);
1282 ///
1283 /// let resp = ctx
1284 /// .option_chain_info_by_date("AAPL.US", date!(2023 - 01 - 20), false)
1285 /// .await?;
1286 /// println!("{:?}", resp);
1287 /// # Ok::<_, Box<dyn std::error::Error>>(())
1288 /// # });
1289 /// ```
1290 pub async fn option_chain_info_by_date(
1291 &self,
1292 symbol: impl Into<String>,
1293 expiry_date: Date,
1294 standard_only: bool,
1295 ) -> Result<Vec<OptionChainContract>> {
1296 #[derive(Debug, Serialize)]
1297 struct Request {
1298 symbol: String,
1299 expiry_date: String,
1300 // `false` and an omitted field mean the same thing to the
1301 // endpoint, so send nothing rather than `"standard_only": false`.
1302 #[serde(skip_serializing_if = "std::ops::Not::not")]
1303 standard_only: bool,
1304 }
1305
1306 #[derive(Debug, Deserialize)]
1307 struct RawOptionChainContract {
1308 #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1309 symbol: String,
1310 expiry_date: String,
1311 #[serde(with = "crate::serde_utils::decimal_empty_is_0")]
1312 strike_price: Decimal,
1313 direction: String,
1314 // Both of these are documented as an empty string for the common
1315 // case, so tolerate an explicit `null` as well.
1316 #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1317 option_type: String,
1318 #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1319 standard_attr: String,
1320 #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1321 days_to_expiry: i32,
1322 }
1323
1324 #[derive(Debug, Deserialize)]
1325 struct Response {
1326 #[serde(default, deserialize_with = "crate::serde_utils::null_as_default")]
1327 list: Vec<RawOptionChainContract>,
1328 }
1329
1330 self.0
1331 .http_cli
1332 .request(Method::POST, "/v1/quote/options/strikes")
1333 .body(Json(Request {
1334 symbol: symbol.into(),
1335 expiry_date: format_date(expiry_date),
1336 standard_only,
1337 }))
1338 .response::<Json<Response>>()
1339 .send()
1340 .with_subscriber(self.0.log_subscriber.clone())
1341 .await?
1342 .0
1343 .list
1344 .into_iter()
1345 .map(|row| {
1346 Ok(OptionChainContract {
1347 symbol: row.symbol,
1348 expiry_date: parse_date(&row.expiry_date)
1349 .map_err(|err| Error::parse_field_error("expiry_date", err))?,
1350 strike_price: row.strike_price,
1351 direction: OptionDirection::from_str(&row.direction).unwrap_or_default(),
1352 option_type: OptionExpiryCycleType::from_str(&row.option_type)
1353 .unwrap_or_default(),
1354 standard_attr: OptionStandardAttr::from_str(&row.standard_attr)
1355 .unwrap_or_default(),
1356 days_to_expiry: row.days_to_expiry,
1357 })
1358 })
1359 .collect()
1360 }
1361
1362 /// Get warrant issuers
1363 ///
1364 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/issuer>
1365 ///
1366 /// # Examples
1367 ///
1368 /// ```no_run
1369 /// use std::sync::Arc;
1370 ///
1371 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
1372 ///
1373 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1374 /// let oauth = OAuthBuilder::new("your-client-id")
1375 /// .build(|url| println!("Visit: {url}"))
1376 /// .await?;
1377 /// let config = Arc::new(Config::from_oauth(oauth));
1378 /// let (ctx, _) = QuoteContext::new(config);
1379 ///
1380 /// let resp = ctx.warrant_issuers().await?;
1381 /// println!("{:?}", resp);
1382 /// # Ok::<_, Box<dyn std::error::Error>>(())
1383 /// # });
1384 /// ```
1385 pub async fn warrant_issuers(&self) -> Result<Vec<IssuerInfo>> {
1386 self.0
1387 .cache_issuers
1388 .get_or_update(|| async {
1389 let resp = self
1390 .request_without_body::<quote::IssuerInfoResponse>(
1391 cmd_code::GET_WARRANT_ISSUER_IDS,
1392 )
1393 .await?;
1394 Ok(resp.issuer_info.into_iter().map(Into::into).collect())
1395 })
1396 .await
1397 }
1398
1399 /// Query warrant list
1400 #[allow(clippy::too_many_arguments)]
1401 pub async fn warrant_list(
1402 &self,
1403 symbol: impl Into<String>,
1404 sort_by: WarrantSortBy,
1405 sort_order: SortOrderType,
1406 warrant_type: Option<&[WarrantType]>,
1407 issuer: Option<&[i32]>,
1408 expiry_date: Option<&[FilterWarrantExpiryDate]>,
1409 price_type: Option<&[FilterWarrantInOutBoundsType]>,
1410 status: Option<&[WarrantStatus]>,
1411 ) -> Result<Vec<WarrantInfo>> {
1412 let resp = self
1413 .request::<_, quote::WarrantFilterListResponse>(
1414 cmd_code::GET_FILTERED_WARRANT,
1415 quote::WarrantFilterListRequest {
1416 symbol: symbol.into(),
1417 filter_config: Some(quote::FilterConfig {
1418 sort_by: sort_by.into(),
1419 sort_order: sort_order.into(),
1420 sort_offset: 0,
1421 sort_count: 0,
1422 r#type: warrant_type
1423 .map(|types| types.iter().map(|ty| (*ty).into()).collect())
1424 .unwrap_or_default(),
1425 issuer: issuer.map(|types| types.to_vec()).unwrap_or_default(),
1426 expiry_date: expiry_date
1427 .map(|e| e.iter().map(|e| (*e).into()).collect())
1428 .unwrap_or_default(),
1429 price_type: price_type
1430 .map(|types| types.iter().map(|ty| (*ty).into()).collect())
1431 .unwrap_or_default(),
1432 status: status
1433 .map(|status| status.iter().map(|status| (*status).into()).collect())
1434 .unwrap_or_default(),
1435 }),
1436 language: self.0.language.into(),
1437 },
1438 )
1439 .await?;
1440 resp.warrant_list
1441 .into_iter()
1442 .map(TryInto::try_into)
1443 .collect::<Result<Vec<_>>>()
1444 }
1445
1446 /// Get trading session of the day
1447 ///
1448 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/trade-session>
1449 ///
1450 /// # Examples
1451 ///
1452 /// ```no_run
1453 /// use std::sync::Arc;
1454 ///
1455 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
1456 ///
1457 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1458 /// let oauth = OAuthBuilder::new("your-client-id")
1459 /// .build(|url| println!("Visit: {url}"))
1460 /// .await?;
1461 /// let config = Arc::new(Config::from_oauth(oauth));
1462 /// let (ctx, _) = QuoteContext::new(config);
1463 ///
1464 /// let resp = ctx.trading_session().await?;
1465 /// println!("{:?}", resp);
1466 /// # Ok::<_, Box<dyn std::error::Error>>(())
1467 /// # });
1468 /// ```
1469 pub async fn trading_session(&self) -> Result<Vec<MarketTradingSession>> {
1470 self.0
1471 .cache_trading_session
1472 .get_or_update(|| async {
1473 let resp = self
1474 .request_without_body::<quote::MarketTradePeriodResponse>(
1475 cmd_code::GET_TRADING_SESSION,
1476 )
1477 .await?;
1478 resp.market_trade_session
1479 .into_iter()
1480 .map(TryInto::try_into)
1481 .collect::<Result<Vec<_>>>()
1482 })
1483 .await
1484 }
1485
1486 /// Get market trading days
1487 ///
1488 /// The interval must be less than one month, and only the most recent year
1489 /// is supported.
1490 ///
1491 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/trade-day>
1492 ///
1493 /// # Examples
1494 ///
1495 /// ```no_run
1496 /// use std::sync::Arc;
1497 ///
1498 /// use longport::{Config, Market, oauth::OAuthBuilder, quote::QuoteContext};
1499 /// use time::macros::date;
1500 ///
1501 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1502 /// let oauth = OAuthBuilder::new("your-client-id")
1503 /// .build(|url| println!("Visit: {url}"))
1504 /// .await?;
1505 /// let config = Arc::new(Config::from_oauth(oauth));
1506 /// let (ctx, _) = QuoteContext::new(config);
1507 ///
1508 /// let resp = ctx
1509 /// .trading_days(Market::HK, date!(2022 - 01 - 20), date!(2022 - 02 - 20))
1510 /// .await?;
1511 /// println!("{:?}", resp);
1512 /// # Ok::<_, Box<dyn std::error::Error>>(())
1513 /// # });
1514 /// ```
1515 pub async fn trading_days(
1516 &self,
1517 market: Market,
1518 begin: Date,
1519 end: Date,
1520 ) -> Result<MarketTradingDays> {
1521 let resp = self
1522 .request::<_, quote::MarketTradeDayResponse>(
1523 cmd_code::GET_TRADING_DAYS,
1524 quote::MarketTradeDayRequest {
1525 market: market.to_string(),
1526 beg_day: format_date(begin),
1527 end_day: format_date(end),
1528 },
1529 )
1530 .await?;
1531 let trading_days = resp
1532 .trade_day
1533 .iter()
1534 .map(|value| {
1535 parse_date(value).map_err(|err| Error::parse_field_error("trade_day", err))
1536 })
1537 .collect::<Result<Vec<_>>>()?;
1538 let half_trading_days = resp
1539 .half_trade_day
1540 .iter()
1541 .map(|value| {
1542 parse_date(value).map_err(|err| Error::parse_field_error("half_trade_day", err))
1543 })
1544 .collect::<Result<Vec<_>>>()?;
1545 Ok(MarketTradingDays {
1546 trading_days,
1547 half_trading_days,
1548 })
1549 }
1550
1551 /// Get capital flow intraday
1552 ///
1553 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/capital-flow-intraday>
1554 ///
1555 /// # Examples
1556 ///
1557 /// ```no_run
1558 /// use std::sync::Arc;
1559 ///
1560 /// use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config};
1561 ///
1562 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1563 /// let oauth = OAuthBuilder::new("your-client-id")
1564 /// .build(|url| println!("Visit: {url}"))
1565 /// .await?;
1566 /// let config = Arc::new(Config::from_oauth(oauth));
1567 /// let (ctx, _) = QuoteContext::new(config);
1568 ///
1569 /// let resp = ctx.capital_flow("700.HK").await?;
1570 /// println!("{:?}", resp);
1571 /// # Ok::<_, Box<dyn std::error::Error>>(())
1572 /// # });
1573 pub async fn capital_flow(&self, symbol: impl Into<String>) -> Result<Vec<CapitalFlowLine>> {
1574 self.request::<_, quote::CapitalFlowIntradayResponse>(
1575 cmd_code::GET_CAPITAL_FLOW_INTRADAY,
1576 quote::CapitalFlowIntradayRequest {
1577 symbol: symbol.into(),
1578 },
1579 )
1580 .await?
1581 .capital_flow_lines
1582 .into_iter()
1583 .map(TryInto::try_into)
1584 .collect()
1585 }
1586
1587 /// Get capital distribution
1588 ///
1589 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/capital-distribution>
1590 ///
1591 /// # Examples
1592 ///
1593 /// ```no_run
1594 /// use std::sync::Arc;
1595 ///
1596 /// use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config};
1597 ///
1598 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1599 /// let oauth = OAuthBuilder::new("your-client-id")
1600 /// .build(|url| println!("Visit: {url}"))
1601 /// .await?;
1602 /// let config = Arc::new(Config::from_oauth(oauth));
1603 /// let (ctx, _) = QuoteContext::new(config);
1604 ///
1605 /// let resp = ctx.capital_distribution("700.HK").await?;
1606 /// println!("{:?}", resp);
1607 /// # Ok::<_, Box<dyn std::error::Error>>(())
1608 /// # });
1609 pub async fn capital_distribution(
1610 &self,
1611 symbol: impl Into<String>,
1612 ) -> Result<CapitalDistributionResponse> {
1613 self.request::<_, quote::CapitalDistributionResponse>(
1614 cmd_code::GET_SECURITY_CAPITAL_DISTRIBUTION,
1615 quote::SecurityRequest {
1616 symbol: symbol.into(),
1617 },
1618 )
1619 .await?
1620 .try_into()
1621 }
1622
1623 /// Get calc indexes
1624 pub async fn calc_indexes<I, T, J>(
1625 &self,
1626 symbols: I,
1627 indexes: J,
1628 ) -> Result<Vec<SecurityCalcIndex>>
1629 where
1630 I: IntoIterator<Item = T>,
1631 T: Into<String>,
1632 J: IntoIterator<Item = CalcIndex>,
1633 {
1634 let indexes = indexes.into_iter().collect::<Vec<CalcIndex>>();
1635 let resp: quote::SecurityCalcQuoteResponse = self
1636 .request(
1637 cmd_code::GET_CALC_INDEXES,
1638 quote::SecurityCalcQuoteRequest {
1639 symbols: symbols.into_iter().map(Into::into).collect(),
1640 calc_index: indexes
1641 .iter()
1642 .map(|i| quote::CalcIndex::from(*i).into())
1643 .collect(),
1644 },
1645 )
1646 .await?;
1647
1648 Ok(resp
1649 .security_calc_index
1650 .into_iter()
1651 .map(|resp| SecurityCalcIndex::from_proto(resp, &indexes))
1652 .collect())
1653 }
1654
1655 /// Get watchlist
1656 ///
1657 /// Reference: <https://open.longportapp.com/en/docs/quote/individual/watchlist_groups>
1658 ///
1659 /// # Examples
1660 ///
1661 /// ```no_run
1662 /// use std::sync::Arc;
1663 ///
1664 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
1665 ///
1666 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1667 /// let oauth = OAuthBuilder::new("your-client-id")
1668 /// .build(|url| println!("Visit: {url}"))
1669 /// .await?;
1670 /// let config = Arc::new(Config::from_oauth(oauth));
1671 /// let (ctx, _) = QuoteContext::new(config);
1672 ///
1673 /// let resp = ctx.watchlist().await?;
1674 /// println!("{:?}", resp);
1675 /// # Ok::<_, Box<dyn std::error::Error>>(())
1676 /// # });
1677 /// ```
1678 pub async fn watchlist(&self) -> Result<Vec<WatchlistGroup>> {
1679 #[derive(Debug, Deserialize)]
1680 struct Response {
1681 groups: Vec<WatchlistGroup>,
1682 }
1683
1684 let resp = self
1685 .0
1686 .http_cli
1687 .request(Method::GET, "/v1/watchlist/groups")
1688 .response::<Json<Response>>()
1689 .send()
1690 .with_subscriber(self.0.log_subscriber.clone())
1691 .await?;
1692 Ok(resp.0.groups)
1693 }
1694
1695 /// Create watchlist group
1696 ///
1697 /// Reference: <https://open.longportapp.com/en/docs/quote/individual/watchlist_create_group>
1698 ///
1699 /// # Examples
1700 ///
1701 /// ```no_run
1702 /// use std::sync::Arc;
1703 ///
1704 /// use longport::{
1705 /// Config,
1706 /// oauth::OAuthBuilder,
1707 /// quote::{QuoteContext, RequestCreateWatchlistGroup},
1708 /// };
1709 ///
1710 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1711 /// let oauth = OAuthBuilder::new("your-client-id")
1712 /// .build(|url| println!("Visit: {url}"))
1713 /// .await?;
1714 /// let config = Arc::new(Config::from_oauth(oauth));
1715 /// let (ctx, _) = QuoteContext::new(config);
1716 ///
1717 /// let req = RequestCreateWatchlistGroup::new("Watchlist1").securities(["700.HK", "BABA.US"]);
1718 /// let group_id = ctx.create_watchlist_group(req).await?;
1719 /// println!("{}", group_id);
1720 /// # Ok::<_, Box<dyn std::error::Error>>(())
1721 /// # });
1722 /// ```
1723 pub async fn create_watchlist_group(&self, req: RequestCreateWatchlistGroup) -> Result<i64> {
1724 #[derive(Debug, Serialize)]
1725 struct RequestCreate {
1726 name: String,
1727 #[serde(skip_serializing_if = "Option::is_none")]
1728 securities: Option<Vec<String>>,
1729 }
1730
1731 #[derive(Debug, Deserialize)]
1732 struct Response {
1733 #[serde(with = "serde_utils::int64_str")]
1734 id: i64,
1735 }
1736
1737 let Json(Response { id }) = self
1738 .0
1739 .http_cli
1740 .request(Method::POST, "/v1/watchlist/groups")
1741 .body(Json(RequestCreate {
1742 name: req.name,
1743 securities: req.securities,
1744 }))
1745 .response::<Json<Response>>()
1746 .send()
1747 .with_subscriber(self.0.log_subscriber.clone())
1748 .await?;
1749
1750 Ok(id)
1751 }
1752
1753 /// Delete watchlist group
1754 ///
1755 /// Reference: <https://open.longportapp.com/en/docs/quote/individual/watchlist_delete_group>
1756 ///
1757 /// # Examples
1758 ///
1759 /// ```no_run
1760 /// use std::sync::Arc;
1761 ///
1762 /// use longport::{Config, oauth::OAuthBuilder, quote::QuoteContext};
1763 ///
1764 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1765 /// let oauth = OAuthBuilder::new("your-client-id")
1766 /// .build(|url| println!("Visit: {url}"))
1767 /// .await?;
1768 /// let config = Arc::new(Config::from_oauth(oauth));
1769 /// let (ctx, _) = QuoteContext::new(config);
1770 ///
1771 /// ctx.delete_watchlist_group(10086, true).await?;
1772 /// # Ok::<_, Box<dyn std::error::Error>>(())
1773 /// # });
1774 /// ```
1775 pub async fn delete_watchlist_group(&self, id: i64, purge: bool) -> Result<()> {
1776 #[derive(Debug, Serialize)]
1777 struct Request {
1778 id: i64,
1779 purge: bool,
1780 }
1781
1782 Ok(self
1783 .0
1784 .http_cli
1785 .request(Method::DELETE, "/v1/watchlist/groups")
1786 .query_params(Request { id, purge })
1787 .send()
1788 .with_subscriber(self.0.log_subscriber.clone())
1789 .await?)
1790 }
1791
1792 /// Update watchlist group
1793 ///
1794 /// Reference: <https://open.longportapp.com/en/docs/quote/individual/watchlist_update_group>
1795 /// Reference: <https://open.longportapp.com/en/docs/quote/individual/watchlist_update_group_securities>
1796 ///
1797 /// # Examples
1798 ///
1799 /// ```no_run
1800 /// use std::sync::Arc;
1801 ///
1802 /// use longport::{
1803 /// Config,
1804 /// oauth::OAuthBuilder,
1805 /// quote::{QuoteContext, RequestUpdateWatchlistGroup},
1806 /// };
1807 ///
1808 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1809 /// let oauth = OAuthBuilder::new("your-client-id")
1810 /// .build(|url| println!("Visit: {url}"))
1811 /// .await?;
1812 /// let config = Arc::new(Config::from_oauth(oauth));
1813 /// let (ctx, _) = QuoteContext::new(config);
1814 /// let req = RequestUpdateWatchlistGroup::new(10086)
1815 /// .name("Watchlist2")
1816 /// .securities(["700.HK", "BABA.US"]);
1817 /// ctx.update_watchlist_group(req).await?;
1818 /// # Ok::<_, Box<dyn std::error::Error>>(())
1819 /// # });
1820 /// ```
1821 pub async fn update_watchlist_group(&self, req: RequestUpdateWatchlistGroup) -> Result<()> {
1822 #[derive(Debug, Serialize)]
1823 struct RequestUpdate {
1824 id: i64,
1825 #[serde(skip_serializing_if = "Option::is_none")]
1826 name: Option<String>,
1827 #[serde(skip_serializing_if = "Option::is_none")]
1828 securities: Option<Vec<String>>,
1829 #[serde(skip_serializing_if = "Option::is_none")]
1830 mode: Option<SecuritiesUpdateMode>,
1831 }
1832
1833 self.0
1834 .http_cli
1835 .request(Method::PUT, "/v1/watchlist/groups")
1836 .body(Json(RequestUpdate {
1837 id: req.id,
1838 name: req.name,
1839 mode: req.securities.is_some().then_some(req.mode),
1840 securities: req.securities,
1841 }))
1842 .send()
1843 .with_subscriber(self.0.log_subscriber.clone())
1844 .await?;
1845
1846 Ok(())
1847 }
1848
1849 /// Get security list
1850 pub async fn security_list(
1851 &self,
1852 market: Market,
1853 category: impl Into<Option<SecurityListCategory>>,
1854 ) -> Result<Vec<Security>> {
1855 #[derive(Debug, Serialize)]
1856 struct Request {
1857 market: Market,
1858 #[serde(skip_serializing_if = "Option::is_none")]
1859 category: Option<SecurityListCategory>,
1860 }
1861
1862 #[derive(Debug, Deserialize)]
1863 struct Response {
1864 list: Vec<Security>,
1865 }
1866
1867 Ok(self
1868 .0
1869 .http_cli
1870 .request(Method::GET, "/v1/quote/get_security_list")
1871 .query_params(Request {
1872 market,
1873 category: category.into(),
1874 })
1875 .response::<Json<Response>>()
1876 .send()
1877 .with_subscriber(self.0.log_subscriber.clone())
1878 .await?
1879 .0
1880 .list)
1881 }
1882
1883 /// Get filings list
1884 pub async fn filings(&self, symbol: impl Into<String>) -> Result<Vec<FilingItem>> {
1885 #[derive(Debug, Serialize)]
1886 struct Request {
1887 symbol: String,
1888 }
1889
1890 #[derive(Debug, Deserialize)]
1891 struct Response {
1892 items: Vec<FilingItem>,
1893 }
1894
1895 Ok(self
1896 .0
1897 .http_cli
1898 .request(Method::GET, "/v1/quote/filings")
1899 .query_params(Request {
1900 symbol: symbol.into(),
1901 })
1902 .response::<Json<Response>>()
1903 .send()
1904 .with_subscriber(self.0.log_subscriber.clone())
1905 .await?
1906 .0
1907 .items)
1908 }
1909
1910 /// Get current market temperature
1911 ///
1912 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/market_temperature>
1913 ///
1914 /// # Examples
1915 ///
1916 /// ```no_run
1917 /// use std::sync::Arc;
1918 ///
1919 /// use longport::{Config, Market, oauth::OAuthBuilder, quote::QuoteContext};
1920 ///
1921 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1922 /// let oauth = OAuthBuilder::new("your-client-id")
1923 /// .build(|url| println!("Visit: {url}"))
1924 /// .await?;
1925 /// let config = Arc::new(Config::from_oauth(oauth));
1926 /// let (ctx, _) = QuoteContext::new(config);
1927 ///
1928 /// let resp = ctx.market_temperature(Market::HK).await?;
1929 /// println!("{:?}", resp);
1930 /// # Ok::<_, Box<dyn std::error::Error>>(())
1931 /// # });
1932 /// ```
1933 pub async fn market_temperature(&self, market: Market) -> Result<MarketTemperature> {
1934 #[derive(Debug, Serialize)]
1935 struct Request {
1936 market: Market,
1937 }
1938
1939 Ok(self
1940 .0
1941 .http_cli
1942 .request(Method::GET, "/v1/quote/market_temperature")
1943 .query_params(Request { market })
1944 .response::<Json<MarketTemperature>>()
1945 .send()
1946 .with_subscriber(self.0.log_subscriber.clone())
1947 .await?
1948 .0)
1949 }
1950
1951 /// Get historical market temperature
1952 ///
1953 /// Reference: <https://open.longportapp.com/en/docs/quote/pull/history_market_temperature>
1954 ///
1955 /// # Examples
1956 ///
1957 /// ```no_run
1958 /// use std::sync::Arc;
1959 ///
1960 /// use longport::{Config, Market, oauth::OAuthBuilder, quote::QuoteContext};
1961 /// use time::macros::date;
1962 ///
1963 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
1964 /// let oauth = OAuthBuilder::new("your-client-id")
1965 /// .build(|url| println!("Visit: {url}"))
1966 /// .await?;
1967 /// let config = Arc::new(Config::from_oauth(oauth));
1968 /// let (ctx, _) = QuoteContext::new(config);
1969 ///
1970 /// let resp = ctx
1971 /// .history_market_temperature(Market::HK, date!(2023 - 01 - 01), date!(2023 - 01 - 31))
1972 /// .await?;
1973 /// println!("{:?}", resp);
1974 /// # Ok::<_, Box<dyn std::error::Error>>(())
1975 /// # });
1976 /// ```
1977 pub async fn history_market_temperature(
1978 &self,
1979 market: Market,
1980 start_date: Date,
1981 end_date: Date,
1982 ) -> Result<HistoryMarketTemperatureResponse> {
1983 #[derive(Debug, Serialize)]
1984 struct Request {
1985 market: Market,
1986 start_date: String,
1987 end_date: String,
1988 }
1989
1990 Ok(self
1991 .0
1992 .http_cli
1993 .request(Method::GET, "/v1/quote/history_market_temperature")
1994 .query_params(Request {
1995 market,
1996 start_date: format_date(start_date),
1997 end_date: format_date(end_date),
1998 })
1999 .response::<Json<HistoryMarketTemperatureResponse>>()
2000 .send()
2001 .with_subscriber(self.0.log_subscriber.clone())
2002 .await?
2003 .0)
2004 }
2005
2006 /// Get real-time quotes
2007 ///
2008 /// Get real-time quotes of the subscribed symbols, it always returns the
2009 /// data in the local storage.
2010 ///
2011 /// # Examples
2012 ///
2013 /// ```no_run
2014 /// use std::{sync::Arc, time::Duration};
2015 ///
2016 /// use longport::{
2017 /// Config,
2018 /// oauth::OAuthBuilder,
2019 /// quote::{QuoteContext, SubFlags},
2020 /// };
2021 ///
2022 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
2023 /// let oauth = OAuthBuilder::new("your-client-id")
2024 /// .build(|url| println!("Visit: {url}"))
2025 /// .await?;
2026 /// let config = Arc::new(Config::from_oauth(oauth));
2027 /// let (ctx, _) = QuoteContext::new(config);
2028 ///
2029 /// ctx.subscribe(["700.HK", "AAPL.US"], SubFlags::QUOTE)
2030 /// .await?;
2031 /// tokio::time::sleep(Duration::from_secs(5)).await;
2032 ///
2033 /// let resp = ctx.realtime_quote(["700.HK", "AAPL.US"]).await?;
2034 /// println!("{:?}", resp);
2035 /// # Ok::<_, Box<dyn std::error::Error>>(())
2036 /// # });
2037 /// ```
2038 pub async fn realtime_quote<I, T>(&self, symbols: I) -> Result<Vec<RealtimeQuote>>
2039 where
2040 I: IntoIterator<Item = T>,
2041 T: Into<String>,
2042 {
2043 let (reply_tx, reply_rx) = oneshot::channel();
2044 self.0
2045 .command_tx
2046 .send(Command::GetRealtimeQuote {
2047 symbols: symbols.into_iter().map(Into::into).collect(),
2048 reply_tx,
2049 })
2050 .map_err(|_| WsClientError::ClientClosed)?;
2051 Ok(reply_rx.await.map_err(|_| WsClientError::ClientClosed)?)
2052 }
2053
2054 /// Get real-time depth
2055 ///
2056 /// Get real-time depth of the subscribed symbols, it always returns the
2057 /// data in the local storage.
2058 ///
2059 /// # Examples
2060 ///
2061 /// ```no_run
2062 /// use std::{sync::Arc, time::Duration};
2063 ///
2064 /// use longport::{
2065 /// Config,
2066 /// oauth::OAuthBuilder,
2067 /// quote::{QuoteContext, SubFlags},
2068 /// };
2069 ///
2070 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
2071 /// let oauth = OAuthBuilder::new("your-client-id")
2072 /// .build(|url| println!("Visit: {url}"))
2073 /// .await?;
2074 /// let config = Arc::new(Config::from_oauth(oauth));
2075 /// let (ctx, _) = QuoteContext::new(config);
2076 ///
2077 /// ctx.subscribe(["700.HK", "AAPL.US"], SubFlags::DEPTH)
2078 /// .await?;
2079 /// tokio::time::sleep(Duration::from_secs(5)).await;
2080 ///
2081 /// let resp = ctx.realtime_depth("700.HK").await?;
2082 /// println!("{:?}", resp);
2083 /// # Ok::<_, Box<dyn std::error::Error>>(())
2084 /// # });
2085 /// ```
2086 pub async fn realtime_depth(&self, symbol: impl Into<String>) -> Result<SecurityDepth> {
2087 let (reply_tx, reply_rx) = oneshot::channel();
2088 self.0
2089 .command_tx
2090 .send(Command::GetRealtimeDepth {
2091 symbol: symbol.into(),
2092 reply_tx,
2093 })
2094 .map_err(|_| WsClientError::ClientClosed)?;
2095 Ok(reply_rx.await.map_err(|_| WsClientError::ClientClosed)?)
2096 }
2097
2098 /// Get real-time trades
2099 ///
2100 /// Get real-time trades of the subscribed symbols, it always returns the
2101 /// data in the local storage.
2102 ///
2103 /// # Examples
2104 ///
2105 /// ```no_run
2106 /// use std::{sync::Arc, time::Duration};
2107 ///
2108 /// use longport::{
2109 /// Config,
2110 /// oauth::OAuthBuilder,
2111 /// quote::{QuoteContext, SubFlags},
2112 /// };
2113 ///
2114 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
2115 /// let oauth = OAuthBuilder::new("your-client-id")
2116 /// .build(|url| println!("Visit: {url}"))
2117 /// .await?;
2118 /// let config = Arc::new(Config::from_oauth(oauth));
2119 /// let (ctx, _) = QuoteContext::new(config);
2120 ///
2121 /// ctx.subscribe(["700.HK", "AAPL.US"], SubFlags::TRADE)
2122 /// .await?;
2123 /// tokio::time::sleep(Duration::from_secs(5)).await;
2124 ///
2125 /// let resp = ctx.realtime_trades("700.HK", 10).await?;
2126 /// println!("{:?}", resp);
2127 /// # Ok::<_, Box<dyn std::error::Error>>(())
2128 /// # });
2129 /// ```
2130 pub async fn realtime_trades(
2131 &self,
2132 symbol: impl Into<String>,
2133 count: usize,
2134 ) -> Result<Vec<Trade>> {
2135 let (reply_tx, reply_rx) = oneshot::channel();
2136 self.0
2137 .command_tx
2138 .send(Command::GetRealtimeTrade {
2139 symbol: symbol.into(),
2140 count,
2141 reply_tx,
2142 })
2143 .map_err(|_| WsClientError::ClientClosed)?;
2144 Ok(reply_rx.await.map_err(|_| WsClientError::ClientClosed)?)
2145 }
2146
2147 /// Get real-time broker queue
2148 ///
2149 ///
2150 /// Get real-time broker queue of the subscribed symbols, it always returns
2151 /// the data in the local storage.
2152 ///
2153 /// # Examples
2154 ///
2155 /// ```no_run
2156 /// use std::{sync::Arc, time::Duration};
2157 ///
2158 /// use longport::{
2159 /// Config,
2160 /// oauth::OAuthBuilder,
2161 /// quote::{QuoteContext, SubFlags},
2162 /// };
2163 ///
2164 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
2165 /// let oauth = OAuthBuilder::new("your-client-id")
2166 /// .build(|url| println!("Visit: {url}"))
2167 /// .await?;
2168 /// let config = Arc::new(Config::from_oauth(oauth));
2169 /// let (ctx, _) = QuoteContext::new(config);
2170 ///
2171 /// ctx.subscribe(["700.HK", "AAPL.US"], SubFlags::BROKER)
2172 /// .await?;
2173 /// tokio::time::sleep(Duration::from_secs(5)).await;
2174 ///
2175 /// let resp = ctx.realtime_brokers("700.HK").await?;
2176 /// println!("{:?}", resp);
2177 /// # Ok::<_, Box<dyn std::error::Error>>(())
2178 /// # });
2179 /// ```
2180 pub async fn realtime_brokers(&self, symbol: impl Into<String>) -> Result<SecurityBrokers> {
2181 let (reply_tx, reply_rx) = oneshot::channel();
2182 self.0
2183 .command_tx
2184 .send(Command::GetRealtimeBrokers {
2185 symbol: symbol.into(),
2186 reply_tx,
2187 })
2188 .map_err(|_| WsClientError::ClientClosed)?;
2189 Ok(reply_rx.await.map_err(|_| WsClientError::ClientClosed)?)
2190 }
2191
2192 /// Get real-time candlesticks
2193 ///
2194 /// Get real-time candlesticks of the subscribed symbols, it always returns
2195 /// the data in the local storage.
2196 ///
2197 /// # Examples
2198 ///
2199 /// ```no_run
2200 /// use std::{sync::Arc, time::Duration};
2201 ///
2202 /// use longport::{
2203 /// Config,
2204 /// oauth::OAuthBuilder,
2205 /// quote::{Period, QuoteContext, TradeSessions},
2206 /// };
2207 ///
2208 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
2209 /// let oauth = OAuthBuilder::new("your-client-id")
2210 /// .build(|url| println!("Visit: {url}"))
2211 /// .await?;
2212 /// let config = Arc::new(Config::from_oauth(oauth));
2213 /// let (ctx, _) = QuoteContext::new(config);
2214 ///
2215 /// ctx.subscribe_candlesticks("AAPL.US", Period::OneMinute, TradeSessions::Intraday)
2216 /// .await?;
2217 /// tokio::time::sleep(Duration::from_secs(5)).await;
2218 ///
2219 /// let resp = ctx
2220 /// .realtime_candlesticks("AAPL.US", Period::OneMinute, 10)
2221 /// .await?;
2222 /// println!("{:?}", resp);
2223 /// # Ok::<_, Box<dyn std::error::Error>>(())
2224 /// # });
2225 /// ```
2226 pub async fn realtime_candlesticks(
2227 &self,
2228 symbol: impl Into<String>,
2229 period: Period,
2230 count: usize,
2231 ) -> Result<Vec<Candlestick>> {
2232 let (reply_tx, reply_rx) = oneshot::channel();
2233 self.0
2234 .command_tx
2235 .send(Command::GetRealtimeCandlesticks {
2236 symbol: symbol.into(),
2237 period,
2238 count,
2239 reply_tx,
2240 })
2241 .map_err(|_| WsClientError::ClientClosed)?;
2242 Ok(reply_rx.await.map_err(|_| WsClientError::ClientClosed)?)
2243 }
2244
2245 // ── short_positions ───────────────────────────────────────────
2246
2247 /// Get short interest data for a US or HK security.
2248 ///
2249 /// Market is inferred from the symbol suffix:
2250 /// - `.HK` → `GET /v1/quote/short-positions/hk`
2251 /// - otherwise → `GET /v1/quote/short-positions/us`
2252 ///
2253 /// `count` controls the number of records returned (1–100, default 20).
2254 pub async fn short_positions(
2255 &self,
2256 symbol: impl Into<String>,
2257 count: u32,
2258 ) -> Result<ShortPositionsResponse> {
2259 use std::time::{SystemTime, UNIX_EPOCH};
2260
2261 let sym = symbol.into();
2262 let is_hk = sym.to_uppercase().ends_with(".HK");
2263 let path = if is_hk {
2264 "/v1/quote/short-positions/hk"
2265 } else {
2266 "/v1/quote/short-positions/us"
2267 };
2268 let ts = SystemTime::now()
2269 .duration_since(UNIX_EPOCH)
2270 .map(|d| d.as_secs())
2271 .unwrap_or(0);
2272
2273 #[derive(serde::Serialize)]
2274 struct Query {
2275 symbol: String,
2276 last_timestamp: String,
2277 count: u32,
2278 }
2279 // Response: {"symbol":"AAPL.US","data":[{...}]} — only `data` is used.
2280 let outer: serde_json::Value = self
2281 .0
2282 .http_cli
2283 .request(Method::GET, path)
2284 .query_params(Query {
2285 symbol: sym.clone(),
2286 last_timestamp: ts.to_string(),
2287 count,
2288 })
2289 .response::<Json<serde_json::Value>>()
2290 .send()
2291 .with_subscriber(self.0.log_subscriber.clone())
2292 .await?
2293 .0;
2294 let empty = vec![];
2295 let raw = outer["data"].as_array().unwrap_or(&empty);
2296 let data = raw
2297 .iter()
2298 .map(|v| {
2299 let ts_str = v["timestamp"].as_str().unwrap_or("").to_string();
2300 ShortPositionsItem {
2301 timestamp: unix_secs_to_rfc3339(&ts_str),
2302 rate: v["rate"].as_str().unwrap_or("").to_string(),
2303 close: v["close"].as_str().unwrap_or("").to_string(),
2304 current_shares_short: v["current_shares_short"]
2305 .as_str()
2306 .unwrap_or("")
2307 .to_string(),
2308 avg_daily_share_volume: v["avg_daily_share_volume"]
2309 .as_str()
2310 .unwrap_or("")
2311 .to_string(),
2312 days_to_cover: v["days_to_cover"].as_str().unwrap_or("").to_string(),
2313 amount: v["amount"].as_str().unwrap_or("").to_string(),
2314 balance: v["balance"].as_str().unwrap_or("").to_string(),
2315 cost: v["cost"].as_str().unwrap_or("").to_string(),
2316 }
2317 })
2318 .collect();
2319 Ok(ShortPositionsResponse { data })
2320 }
2321
2322 // ── option_volume ─────────────────────────────────────────────
2323
2324 /// Get real-time option call/put volume for a security.
2325 ///
2326 /// Path: `GET /v1/quote/option-volume-stats`
2327 pub async fn option_volume(&self, symbol: impl Into<String>) -> Result<OptionVolumeStats> {
2328 #[derive(serde::Serialize)]
2329 struct Query {
2330 symbol: String,
2331 }
2332 #[derive(serde::Deserialize)]
2333 struct RawOptionVolumeStats {
2334 c: String,
2335 p: String,
2336 }
2337 let symbol = symbol.into();
2338 let resp = self
2339 .0
2340 .http_cli
2341 .request(Method::GET, "/v1/quote/option-volume-stats")
2342 .query_params(Query {
2343 symbol: symbol.clone(),
2344 })
2345 .response::<Json<RawOptionVolumeStats>>()
2346 .send()
2347 .with_subscriber(self.0.log_subscriber.clone())
2348 .await?;
2349 let raw = resp.0;
2350 Ok(OptionVolumeStats {
2351 symbol,
2352 call_volume: raw.c.parse().unwrap_or(0),
2353 put_volume: raw.p.parse().unwrap_or(0),
2354 })
2355 }
2356
2357 /// Get daily historical option volume for a security.
2358 ///
2359 /// Path: `GET /v1/quote/option-volume-stats/daily`
2360 pub async fn option_volume_daily(
2361 &self,
2362 symbol: impl Into<String>,
2363 timestamp: i64,
2364 count: u32,
2365 ) -> Result<OptionVolumeDaily> {
2366 #[derive(serde::Serialize)]
2367 struct Query {
2368 symbol: String,
2369 timestamp: i64,
2370 line_num: u32,
2371 direction: i32,
2372 }
2373 #[derive(serde::Deserialize)]
2374 struct RawDailyStat {
2375 symbol: String,
2376 timestamp: String,
2377 total_call_volume: String,
2378 total_put_volume: String,
2379 total_call_open_interest: String,
2380 total_put_open_interest: String,
2381 total_volume: String,
2382 total_open_interest: String,
2383 #[serde(deserialize_with = "crate::serde_utils::f64_str::deserialize")]
2384 put_call_volume_ratio: f64,
2385 #[serde(deserialize_with = "crate::serde_utils::f64_str::deserialize")]
2386 put_call_open_interest_ratio: f64,
2387 }
2388 #[derive(serde::Deserialize)]
2389 struct RawOptionVolumeDaily {
2390 stats: Vec<RawDailyStat>,
2391 }
2392 let symbol = symbol.into();
2393 let resp = self
2394 .0
2395 .http_cli
2396 .request(Method::GET, "/v1/quote/option-volume-stats/daily")
2397 .query_params(Query {
2398 symbol: symbol.clone(),
2399 timestamp,
2400 line_num: count,
2401 direction: 1,
2402 })
2403 .response::<Json<RawOptionVolumeDaily>>()
2404 .send()
2405 .with_subscriber(self.0.log_subscriber.clone())
2406 .await?;
2407 let raw = resp.0;
2408 let stats = raw
2409 .stats
2410 .into_iter()
2411 .map(|item| {
2412 let ts: i64 = item.timestamp.parse().unwrap_or(0);
2413 OptionVolumeDailyStat {
2414 symbol: item.symbol,
2415 date: time::OffsetDateTime::from_unix_timestamp(ts)
2416 .unwrap_or(time::OffsetDateTime::UNIX_EPOCH)
2417 .date(),
2418 call_volume: item.total_call_volume.parse().unwrap_or(0),
2419 put_volume: item.total_put_volume.parse().unwrap_or(0),
2420 call_open_interest: item.total_call_open_interest.parse().unwrap_or(0),
2421 put_open_interest: item.total_put_open_interest.parse().unwrap_or(0),
2422 total_volume: item.total_volume.parse().unwrap_or(0),
2423 total_open_interest: item.total_open_interest.parse().unwrap_or(0),
2424 pc_vol: item.put_call_volume_ratio,
2425 pc_oi: item.put_call_open_interest_ratio,
2426 }
2427 })
2428 .collect();
2429 Ok(OptionVolumeDaily { symbol, stats })
2430 }
2431 // ── short_trades ──────────────────────────────────────────────
2432
2433 /// Get short trade records for a HK or US security.
2434 ///
2435 /// The API endpoint is auto-detected from the symbol suffix:
2436 /// `.HK` → `GET /v1/quote/short-trades/hk`,
2437 /// otherwise → `GET /v1/quote/short-trades/us`.
2438 pub async fn short_trades(
2439 &self,
2440 symbol: impl Into<String>,
2441 count: u32,
2442 ) -> Result<ShortTradesResponse> {
2443 use std::time::{SystemTime, UNIX_EPOCH};
2444
2445 #[derive(serde::Serialize)]
2446 struct Query {
2447 symbol: String,
2448 last_timestamp: String,
2449 page_size: String,
2450 }
2451 let sym = symbol.into();
2452 let path = if sym.to_uppercase().ends_with(".HK") {
2453 "/v1/quote/short-trades/hk"
2454 } else {
2455 "/v1/quote/short-trades/us"
2456 };
2457 let ts = SystemTime::now()
2458 .duration_since(UNIX_EPOCH)
2459 .map(|d| d.as_secs())
2460 .unwrap_or(0);
2461 // Response: {"symbol":"00700.HK","data":[{...}]} — only `data` is used.
2462 let outer: serde_json::Value = self
2463 .0
2464 .http_cli
2465 .request(Method::GET, path)
2466 .query_params(Query {
2467 symbol: sym.clone(),
2468 last_timestamp: ts.to_string(),
2469 page_size: count.to_string(),
2470 })
2471 .response::<Json<serde_json::Value>>()
2472 .send()
2473 .with_subscriber(self.0.log_subscriber.clone())
2474 .await?
2475 .0;
2476 let empty = vec![];
2477 let raw = outer["data"].as_array().unwrap_or(&empty);
2478 let data = raw
2479 .iter()
2480 .map(|v| {
2481 let ts_str = v["timestamp"].as_str().unwrap_or("").to_string();
2482 ShortTradesItem {
2483 timestamp: unix_secs_to_rfc3339(&ts_str),
2484 rate: v["rate"].as_str().unwrap_or("").to_string(),
2485 close: v["close"].as_str().unwrap_or("").to_string(),
2486 nus_amount: v["nus_amount"].as_str().unwrap_or("").to_string(),
2487 ny_amount: v["ny_amount"].as_str().unwrap_or("").to_string(),
2488 total_amount: v["total_amount"].as_str().unwrap_or("").to_string(),
2489 amount: v["amount"].as_str().unwrap_or("").to_string(),
2490 balance: v["balance"].as_str().unwrap_or("").to_string(),
2491 }
2492 })
2493 .collect();
2494 Ok(ShortTradesResponse { data })
2495 }
2496
2497 // ── update_pinned ─────────────────────────────────────────────
2498
2499 /// Pin or unpin watchlist securities.
2500 ///
2501 /// Path: `POST /v1/watchlist/pinned`
2502 pub async fn update_pinned(&self, mode: PinnedMode, symbols: Vec<String>) -> Result<()> {
2503 #[derive(Debug, Serialize)]
2504 struct Request {
2505 mode: PinnedMode,
2506 securities: Vec<String>,
2507 }
2508
2509 self.0
2510 .http_cli
2511 .request(Method::POST, "/v1/watchlist/pinned")
2512 .body(Json(Request {
2513 mode,
2514 securities: symbols,
2515 }))
2516 .send()
2517 .with_subscriber(self.0.log_subscriber.clone())
2518 .await?;
2519
2520 Ok(())
2521 }
2522
2523 // ── US-market APIs
2524 // ────────────────────────────────────────────────────────
2525
2526 /// Get cryptocurrency market overview.
2527 ///
2528 /// `symbol` must be in `PAIR.EXCHANGE` format.
2529 /// US DC uses the **BKKT** exchange: e.g. `"BTCUSD.BKKT"` →
2530 /// `"VA/BKKT/BTCUSD"`. Pass the exchange suffix explicitly.
2531 ///
2532 /// Path: `GET /v1/us/gemini/crypto-overview`
2533 ///
2534 /// US token required.
2535 pub async fn us_crypto_overview(
2536 &self,
2537 symbol: impl Into<String>,
2538 ) -> Result<crate::quote::USCryptoOverview> {
2539 #[derive(Serialize)]
2540 struct Query {
2541 symbol: String,
2542 }
2543 Ok(self
2544 .0
2545 .http_cli
2546 .request(Method::GET, "/v1/us/gemini/crypto-overview")
2547 .dc_restrict(DcRegion::Us)
2548 .query_params(Query {
2549 symbol: symbol.into(),
2550 })
2551 .response::<Json<crate::quote::USCryptoOverview>>()
2552 .send()
2553 .with_subscriber(self.0.log_subscriber.clone())
2554 .await?
2555 .0)
2556 }
2557}
2558
2559#[cfg(test)]
2560mod http_request_tests {
2561 use serde_json::json;
2562 use time::macros::datetime;
2563
2564 use super::*;
2565
2566 /// Locks the JSON shape the HTTP transport sends for a top-up offset
2567 /// query: proto field names, numeric enums, New York wall-clock
2568 /// `date`/`minute`, and no `date_request` key.
2569 #[test]
2570 fn history_offset_request_json() {
2571 let req = history_offset_request(
2572 "AAPL.US".to_string(),
2573 Period::OneMinute,
2574 AdjustType::NoAdjust,
2575 false,
2576 Some(datetime!(2026-10-09 03:59)),
2577 16,
2578 TradeSessions::All,
2579 );
2580 let mut v = serde_json::to_value(&req).unwrap();
2581 http_json::strip_nulls(&mut v);
2582 assert_eq!(
2583 v,
2584 json!({
2585 "symbol": "AAPL.US",
2586 "period": quote::Period::OneMinute as i32,
2587 "adjust_type": quote::AdjustType::NoAdjust as i32,
2588 "query_type": quote::HistoryCandlestickQueryType::QueryByOffset as i32,
2589 "offset_request": {
2590 "direction": quote::Direction::Backward as i32,
2591 "date": "20261009",
2592 "minute": "0359",
2593 "count": 16,
2594 },
2595 "trade_session": 100,
2596 })
2597 );
2598 }
2599
2600 /// Request bodies for a few other mapped commands keep proto names, and
2601 /// the warrant filter's `r#type` is sent as `type`.
2602 #[test]
2603 fn request_json_shapes() {
2604 let v = serde_json::to_value(quote::MultiSecurityRequest {
2605 symbol: vec!["700.HK".into()],
2606 })
2607 .unwrap();
2608 assert_eq!(v, json!({ "symbol": ["700.HK"] }));
2609
2610 let v = serde_json::to_value(quote::SecurityIntradayRequest {
2611 symbol: "AAPL.US".into(),
2612 trade_session: TradeSessions::All as i32,
2613 })
2614 .unwrap();
2615 assert_eq!(v, json!({ "symbol": "AAPL.US", "trade_session": 100 }));
2616
2617 let v = serde_json::to_value(quote::FilterConfig {
2618 r#type: vec![0],
2619 ..Default::default()
2620 })
2621 .unwrap();
2622 assert_eq!(v["type"], json!([0]));
2623 }
2624}