Skip to main content

longport/
config.rs

1use std::{
2    collections::HashMap,
3    fmt::{self, Display},
4    path::{Path, PathBuf},
5    str::FromStr,
6    sync::Arc,
7};
8
9pub(crate) use http::{HeaderName, HeaderValue, Request, header};
10use longport_httpcli::{
11    DC_REGION_HEADER, DcRegion, HttpClient, HttpClientConfig, Json, Method, is_cn,
12};
13use longport_oauth::OAuth;
14use num_enum::IntoPrimitive;
15use serde::{Deserialize, Serialize};
16use time::OffsetDateTime;
17use tokio_tungstenite::tungstenite::client::IntoClientRequest;
18use tracing::{Level, Subscriber, subscriber::NoSubscriber};
19use tracing_appender::rolling::{RollingFileAppender, Rotation};
20use tracing_subscriber::{filter::Targets, layer::SubscriberExt};
21
22use crate::error::Result;
23
24const DEFAULT_QUOTE_WS_URL: &str = "wss://openapi-quote.longportapp.com/v2";
25const DEFAULT_TRADE_WS_URL: &str = "wss://openapi-trade.longportapp.com/v2";
26const DEFAULT_QUOTE_WS_URL_CN: &str = "wss://openapi-quote.longport.cn/v2";
27const DEFAULT_TRADE_WS_URL_CN: &str = "wss://openapi-trade.longport.cn/v2";
28
29/// Language identifier
30#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, IntoPrimitive)]
31#[allow(non_camel_case_types)]
32#[repr(i32)]
33pub enum Language {
34    /// zh-CN
35    ZH_CN = 0,
36    /// zh-HK
37    ZH_HK = 2,
38    /// en
39    #[default]
40    EN = 1,
41}
42
43impl Language {
44    pub(crate) fn as_str(&self) -> &'static str {
45        match self {
46            Language::ZH_CN => "zh-CN",
47            Language::ZH_HK => "zh-HK",
48            Language::EN => "en",
49        }
50    }
51}
52
53impl FromStr for Language {
54    type Err = ();
55
56    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
57        match s {
58            "zh-CN" => Ok(Language::ZH_CN),
59            "zh-HK" => Ok(Language::ZH_HK),
60            "en" => Ok(Language::EN),
61            _ => Err(()),
62        }
63    }
64}
65
66impl Display for Language {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(self.as_str())
69    }
70}
71
72/// Push mode for candlestick
73#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
74pub enum PushCandlestickMode {
75    /// Realtime mode
76    #[default]
77    Realtime,
78    /// Confirmed mode
79    Confirmed,
80}
81
82/// Internal authentication mode (not part of the public API)
83pub(crate) enum AuthMode {
84    /// Legacy API Key mode (HMAC-SHA256 signed requests)
85    ApiKey {
86        app_key: String,
87        app_secret: String,
88        access_token: String,
89    },
90    /// OAuth 2.0 mode
91    OAuth(OAuth),
92}
93
94impl Clone for AuthMode {
95    fn clone(&self) -> Self {
96        match self {
97            AuthMode::ApiKey {
98                app_key,
99                app_secret,
100                access_token,
101            } => AuthMode::ApiKey {
102                app_key: app_key.clone(),
103                app_secret: app_secret.clone(),
104                access_token: access_token.clone(),
105            },
106            AuthMode::OAuth(oauth) => AuthMode::OAuth(oauth.clone()),
107        }
108    }
109}
110
111impl fmt::Debug for AuthMode {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self {
114            AuthMode::ApiKey { app_key, .. } => {
115                f.debug_struct("ApiKey").field("app_key", app_key).finish()
116            }
117            AuthMode::OAuth(_) => f.debug_struct("OAuth").finish(),
118        }
119    }
120}
121
122/// Transport used by the [`QuoteContext`](crate::quote::QuoteContext) pull
123/// (request/response) APIs.
124///
125/// Subscriptions, push events, `realtime_*`, `member_id` / `quote_level` /
126/// `quote_package_details` and the few APIs without a REST equivalent always
127/// use the WebSocket connection; this only selects how the other pull APIs
128/// reach the server. Return types are the same either way, and with `Http`
129/// the SDK applies the WebSocket's US overnight rule (overnight data only when
130/// [`Config::enable_overnight`] is set) client-side. Error codes, rate
131/// limiting and some session-specific values can differ; see the changelog.
132#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
133pub enum QuoteTransport {
134    /// Send pull requests over the quote WebSocket connection (default).
135    #[default]
136    WebSocket,
137    /// Send pull requests over HTTP (`POST /quote/*`) where the API has a REST
138    /// equivalent, falling back to the WebSocket for the rest. Using only
139    /// HTTP-backed APIs never opens a WebSocket connection.
140    Http,
141}
142
143impl FromStr for QuoteTransport {
144    type Err = ();
145
146    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
147        match s.to_ascii_lowercase().as_str() {
148            "ws" => Ok(QuoteTransport::WebSocket),
149            "http" => Ok(QuoteTransport::Http),
150            _ => Err(()),
151        }
152    }
153}
154
155/// Configuration options for LongPort SDK
156#[derive(Debug, Clone)]
157pub struct Config {
158    pub(crate) auth: AuthMode,
159    pub(crate) http_url: Option<String>,
160    pub(crate) quote_ws_url: Option<String>,
161    pub(crate) trade_ws_url: Option<String>,
162    pub(crate) enable_overnight: Option<bool>,
163    pub(crate) push_candlestick_mode: Option<PushCandlestickMode>,
164    pub(crate) enable_print_quote_packages: bool,
165    pub(crate) language: Language,
166    pub(crate) log_path: Option<PathBuf>,
167    /// Extra headers injected into every HTTP and WebSocket upgrade request.
168    pub(crate) custom_headers: HashMap<String, String>,
169    pub(crate) enable_papertrading: bool,
170    pub(crate) quote_transport: QuoteTransport,
171}
172
173/// Reads a `LONGPORT_<suffix>` env var. Returns `None` if it is not set.
174fn env_var(suffix: &str) -> Option<String> {
175    std::env::var(format!("LONGPORT_{suffix}")).ok()
176}
177
178/// Like [`env_var`] but returns an error if the variable is not set.
179fn env_var_required(suffix: &str) -> Result<String> {
180    env_var(suffix).ok_or_else(|| {
181        longport_httpcli::HttpClientError::MissingEnvVar {
182            name: format!("LONGPORT_{suffix}"),
183        }
184        .into()
185    })
186}
187
188/// Non-credential environment variables shared by `from_apikey` and
189/// `from_oauth`.  Callers must have already invoked `dotenv::dotenv()`.
190struct ConfigExtras {
191    http_url: Option<String>,
192    quote_ws_url: Option<String>,
193    trade_ws_url: Option<String>,
194    language: Language,
195    enable_overnight: Option<bool>,
196    push_candlestick_mode: Option<PushCandlestickMode>,
197    enable_print_quote_packages: bool,
198    log_path: Option<PathBuf>,
199    enable_papertrading: bool,
200    quote_transport: QuoteTransport,
201}
202
203impl ConfigExtras {
204    fn from_env() -> Self {
205        let language = env_var("LANGUAGE")
206            .and_then(|v| v.parse::<Language>().ok())
207            .unwrap_or(Language::EN);
208        let enable_overnight = env_var("ENABLE_OVERNIGHT").map(|v| v == "true");
209        let push_candlestick_mode = env_var("PUSH_CANDLESTICK_MODE").map(|v| match v.as_str() {
210            "confirmed" => PushCandlestickMode::Confirmed,
211            _ => PushCandlestickMode::Realtime,
212        });
213        let enable_print_quote_packages =
214            env_var("PRINT_QUOTE_PACKAGES").as_deref().unwrap_or("true") == "true";
215        let enable_papertrading = env_var("PAPERTRADING").as_deref() == Some("true");
216        Self {
217            http_url: env_var("HTTP_URL"),
218            quote_ws_url: env_var("QUOTE_WS_URL"),
219            trade_ws_url: env_var("TRADE_WS_URL"),
220            language,
221            enable_overnight,
222            push_candlestick_mode,
223            enable_print_quote_packages,
224            log_path: env_var("LOG_PATH").map(PathBuf::from),
225            enable_papertrading,
226            quote_transport: env_var("QUOTE_TRANSPORT")
227                .and_then(|v| {
228                    let parsed = v.parse().ok();
229                    if parsed.is_none() {
230                        tracing::warn!(value = %v, "invalid LONGPORT_QUOTE_TRANSPORT, using ws");
231                    }
232                    parsed
233                })
234                .unwrap_or_default(),
235        }
236    }
237}
238
239impl Config {
240    /// Create a new `Config` using API Key authentication.
241    ///
242    /// All optional environment variables (`LONGPORT_HTTP_URL`,
243    /// `LONGPORT_LANGUAGE`, `LONGPORT_QUOTE_WS_URL`,
244    /// `LONGPORT_TRADE_WS_URL`, `LONGPORT_ENABLE_OVERNIGHT`,
245    /// `LONGPORT_PUSH_CANDLESTICK_MODE`, `LONGPORT_QUOTE_TRANSPORT`,
246    /// `LONGPORT_PRINT_QUOTE_PACKAGES`, `LONGPORT_LOG_PATH`) are read from
247    /// the environment (or `.env` file) and applied automatically if set.
248    ///
249    /// For OAuth 2.0, use [`Config::from_oauth`] together with
250    /// [`longport::oauth::OAuthBuilder`] instead.
251    pub fn from_apikey(
252        app_key: impl Into<String>,
253        app_secret: impl Into<String>,
254        access_token: impl Into<String>,
255    ) -> Self {
256        let _ = dotenv::dotenv();
257        let extras = ConfigExtras::from_env();
258        Self {
259            auth: AuthMode::ApiKey {
260                app_key: app_key.into(),
261                app_secret: app_secret.into(),
262                access_token: access_token.into(),
263            },
264            http_url: extras.http_url,
265            quote_ws_url: extras.quote_ws_url,
266            trade_ws_url: extras.trade_ws_url,
267            language: extras.language,
268            enable_overnight: extras.enable_overnight,
269            push_candlestick_mode: extras.push_candlestick_mode,
270            enable_print_quote_packages: extras.enable_print_quote_packages,
271            log_path: extras.log_path,
272            custom_headers: Default::default(),
273            enable_papertrading: extras.enable_papertrading,
274            quote_transport: extras.quote_transport,
275        }
276    }
277
278    /// Create a new `Config` for OAuth 2.0 authentication.
279    ///
280    /// All optional environment variables (`LONGPORT_HTTP_URL`,
281    /// `LONGPORT_LANGUAGE`, `LONGPORT_QUOTE_WS_URL`,
282    /// `LONGPORT_TRADE_WS_URL`, `LONGPORT_ENABLE_OVERNIGHT`,
283    /// `LONGPORT_PUSH_CANDLESTICK_MODE`, `LONGPORT_QUOTE_TRANSPORT`,
284    /// `LONGPORT_PRINT_QUOTE_PACKAGES`, `LONGPORT_LOG_PATH`) are read from
285    /// the environment (or `.env` file) and applied automatically if set.
286    ///
287    /// # Arguments
288    ///
289    /// * `oauth` - An [`OAuth`] client obtained from
290    ///   [`longport::oauth::OAuthBuilder`].
291    ///
292    /// # Example
293    ///
294    /// ```rust,no_run
295    /// use std::sync::Arc;
296    ///
297    /// use longport::{Config, oauth::OAuthBuilder};
298    ///
299    /// #[tokio::main]
300    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
301    ///     let oauth = OAuthBuilder::new("your-client-id")
302    ///         .build(|url| println!("Visit: {url}"))
303    ///         .await?;
304    ///     let config = Arc::new(Config::from_oauth(oauth));
305    ///
306    ///     let (ctx, receiver) = longport::quote::QuoteContext::new(config);
307    ///     Ok(())
308    /// }
309    /// ```
310    pub fn from_oauth(oauth: OAuth) -> Self {
311        let _ = dotenv::dotenv();
312        let extras = ConfigExtras::from_env();
313        Self {
314            auth: AuthMode::OAuth(oauth),
315            http_url: extras.http_url,
316            quote_ws_url: extras.quote_ws_url,
317            trade_ws_url: extras.trade_ws_url,
318            language: extras.language,
319            enable_overnight: extras.enable_overnight,
320            push_candlestick_mode: extras.push_candlestick_mode,
321            enable_print_quote_packages: extras.enable_print_quote_packages,
322            log_path: extras.log_path,
323            custom_headers: Default::default(),
324            enable_papertrading: extras.enable_papertrading,
325            quote_transport: extras.quote_transport,
326        }
327    }
328
329    /// Create a new `Config` from environment variables (API Key
330    /// authentication).
331    ///
332    /// It first loads the environment variables from the `.env` file in the
333    /// current directory.
334    ///
335    /// # Variables
336    ///
337    /// - `LONGPORT_APP_KEY` - App key
338    /// - `LONGPORT_APP_SECRET` - App secret
339    /// - `LONGPORT_ACCESS_TOKEN` - Access token
340    /// - `LONGPORT_LANGUAGE` - Language identifier, `zh-CN`, `zh-HK` or `en`
341    ///   (Default: `en`)
342    /// - `LONGPORT_HTTP_URL` - HTTP endpoint url (Default: `https://openapi.longportapp.com`)
343    /// - `LONGPORT_QUOTE_WS_URL` - Quote websocket endpoint url (Default:
344    ///   `wss://openapi-quote.longportapp.com/v2`)
345    /// - `LONGPORT_TRADE_WS_URL` - Trade websocket endpoint url (Default:
346    ///   `wss://openapi-trade.longportapp.com/v2`)
347    /// - `LONGPORT_ENABLE_OVERNIGHT` - Enable overnight quote, `true` or
348    ///   `false` (Default: `false`)
349    /// - `LONGPORT_PUSH_CANDLESTICK_MODE` - `realtime` or `confirmed` (Default:
350    ///   `realtime`)
351    /// - `LONGPORT_QUOTE_TRANSPORT` - Transport for the quote pull APIs, `ws`
352    ///   or `http` (Default: `ws`)
353    /// - `LONGPORT_PRINT_QUOTE_PACKAGES` - Print quote packages when connected,
354    ///   `true` or `false` (Default: `true`)
355    /// - `LONGPORT_LOG_PATH` - Set the path of the log files (Default: `no
356    ///   logs`)
357    ///
358    /// For OAuth 2.0 authentication use [`from_oauth`](Config::from_oauth)
359    /// together with [`OAuthBuilder`](longport_oauth::OAuthBuilder).
360    pub fn from_apikey_env() -> Result<Self> {
361        let _ = dotenv::dotenv();
362
363        let app_key = env_var_required("APP_KEY")?;
364        let app_secret = env_var_required("APP_SECRET")?;
365        let access_token = env_var_required("ACCESS_TOKEN")?;
366        let extras = ConfigExtras::from_env();
367
368        Ok(Config {
369            auth: AuthMode::ApiKey {
370                app_key,
371                app_secret,
372                access_token,
373            },
374            http_url: extras.http_url,
375            quote_ws_url: extras.quote_ws_url,
376            trade_ws_url: extras.trade_ws_url,
377            language: extras.language,
378            enable_overnight: extras.enable_overnight,
379            push_candlestick_mode: extras.push_candlestick_mode,
380            enable_print_quote_packages: extras.enable_print_quote_packages,
381            log_path: extras.log_path,
382            custom_headers: Default::default(),
383            enable_papertrading: extras.enable_papertrading,
384            quote_transport: extras.quote_transport,
385        })
386    }
387
388    /// Specifies the url of the OpenAPI server.
389    ///
390    /// Default: `https://openapi.longportapp.com`
391    ///
392    /// NOTE: Usually you don't need to change it.
393    #[must_use]
394    pub fn http_url(mut self, url: impl Into<String>) -> Self {
395        self.http_url = Some(url.into());
396        self
397    }
398
399    /// Specifies the url of the OpenAPI quote websocket server.
400    ///
401    /// Default: `wss://openapi-quote.longportapp.com`
402    ///
403    /// NOTE: Usually you don't need to change it.
404    #[must_use]
405    pub fn quote_ws_url(self, url: impl Into<String>) -> Self {
406        Self {
407            quote_ws_url: Some(url.into()),
408            ..self
409        }
410    }
411
412    /// Specifies the url of the OpenAPI trade websocket server.
413    ///
414    /// Default: `wss://openapi-trade.longportapp.com/v2`
415    ///
416    /// NOTE: Usually you don't need to change it.
417    #[must_use]
418    pub fn trade_ws_url(self, url: impl Into<String>) -> Self {
419        Self {
420            trade_ws_url: Some(url.into()),
421            ..self
422        }
423    }
424
425    /// Specifies the language
426    ///
427    /// Default: `Language::EN`
428    pub fn language(self, language: Language) -> Self {
429        Self { language, ..self }
430    }
431
432    /// Enable overnight quote
433    ///
434    /// Default: `false`
435    pub fn enable_overnight(self) -> Self {
436        Self {
437            enable_overnight: Some(true),
438            ..self
439        }
440    }
441
442    /// Specifies the push candlestick mode
443    ///
444    /// Default: `PushCandlestickMode::Realtime`
445    pub fn push_candlestick_mode(self, mode: PushCandlestickMode) -> Self {
446        Self {
447            push_candlestick_mode: Some(mode),
448            ..self
449        }
450    }
451
452    /// Disable printing the opened quote packages when connected to the server.
453    pub fn dont_print_quote_packages(self) -> Self {
454        Self {
455            enable_print_quote_packages: false,
456            ..self
457        }
458    }
459
460    /// Enable paper trading mode.
461    ///
462    /// When enabled, all API calls target the paper trading (simulation)
463    /// environment.  The server validates the token: if it belongs to a
464    /// real-money account the server returns an error.
465    ///
466    /// By default this option is disabled (`false`): the server imposes no
467    /// restrictions and accepts requests from both paper trading and real-money
468    /// accounts.
469    ///
470    /// Paper trading users should enable this option as a safety guard to avoid
471    /// accidentally submitting orders against their real-money account.
472    pub fn enable_papertrading(mut self) -> Self {
473        self.enable_papertrading = true;
474        self
475    }
476
477    /// Specifies the transport used by the quote pull APIs.
478    ///
479    /// Default: `QuoteTransport::WebSocket` (or `LONGPORT_QUOTE_TRANSPORT`
480    /// = `ws` / `http`)
481    pub fn quote_transport(self, quote_transport: QuoteTransport) -> Self {
482        Self {
483            quote_transport,
484            ..self
485        }
486    }
487
488    /// Create metadata for auth/reconnect request
489    pub fn create_metadata(&self) -> HashMap<String, String> {
490        let mut metadata = HashMap::new();
491        metadata.insert("accept-language".to_string(), self.language.to_string());
492        if self.enable_overnight.unwrap_or_default() {
493            metadata.insert("need_over_night_quote".to_string(), "true".to_string());
494        }
495        metadata
496    }
497
498    #[inline]
499    pub(crate) fn create_http_client(&self) -> HttpClient {
500        let mut config = match &self.auth {
501            AuthMode::ApiKey {
502                app_key,
503                app_secret,
504                access_token,
505            } => HttpClientConfig::from_apikey(app_key, app_secret, access_token),
506            AuthMode::OAuth(oauth) => HttpClientConfig::from_oauth(oauth.clone()),
507        };
508        if let Some(url) = &self.http_url {
509            config = config.http_url(url.clone());
510        }
511
512        let mut client =
513            HttpClient::new(config).header(header::ACCEPT_LANGUAGE, self.language.as_str());
514        for (key, value) in &self.custom_headers {
515            client = client.header(key.as_str(), value.as_str());
516        }
517        if self.enable_papertrading {
518            client = client.header("x-papertrading", "true");
519        }
520        client
521    }
522
523    /// Gets a new `access_token`
524    ///
525    /// This method is only available when using **Legacy API Key**
526    /// authentication (i.e. [`Config::from_apikey`]). It is not supported
527    /// for OAuth 2.0 mode.
528    ///
529    /// `expired_at` - The expiration time of the access token, defaults to `90`
530    /// days.
531    ///
532    /// Reference: <https://open.longportapp.com/en/docs/refresh-token-api>
533    pub async fn refresh_access_token(&self, expired_at: Option<OffsetDateTime>) -> Result<String> {
534        #[derive(Debug, Serialize)]
535        struct Request {
536            expired_at: String,
537        }
538
539        #[derive(Debug, Deserialize)]
540        struct Response {
541            token: String,
542        }
543
544        let request = Request {
545            expired_at: expired_at
546                .unwrap_or_else(|| OffsetDateTime::now_utc() + time::Duration::days(90))
547                .format(&time::format_description::well_known::Rfc3339)
548                .unwrap(),
549        };
550
551        let new_token = self
552            .create_http_client()
553            .request(Method::GET, "/v1/token/refresh")
554            .query_params(request)
555            .response::<Json<Response>>()
556            .send()
557            .await?
558            .0
559            .token;
560        Ok(new_token)
561    }
562
563    /// Gets a new `access_token`, and also replaces the `access_token` in
564    /// `Config`.
565    ///
566    /// This method is only available when using **Legacy API Key**
567    /// authentication (i.e. [`Config::from_apikey`]). It is not supported
568    /// for OAuth 2.0 mode.
569    ///
570    /// `expired_at` - The expiration time of the access token, defaults to `90`
571    /// days.
572    ///
573    /// Reference: <https://open.longportapp.com/en/docs/refresh-token-api>
574    #[cfg(feature = "blocking")]
575    #[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
576    pub fn refresh_access_token_blocking(
577        &self,
578        expired_at: Option<OffsetDateTime>,
579    ) -> Result<String> {
580        tokio::runtime::Builder::new_current_thread()
581            .enable_all()
582            .build()
583            .expect("create tokio runtime")
584            .block_on(self.refresh_access_token(expired_at))
585    }
586
587    /// Resolve the data-center region from the auth credentials. For OAuth the
588    /// access token is resolved (and refreshed if needed); for legacy API-key
589    /// mode the `app_key`/`app_secret`/`access_token` prefixes are inspected.
590    async fn auth_dc_region(&self) -> DcRegion {
591        match &self.auth {
592            AuthMode::ApiKey {
593                app_key,
594                app_secret,
595                access_token,
596            } => DcRegion::from_credentials(&[app_key, access_token, app_secret]),
597            AuthMode::OAuth(oauth) => oauth
598                .access_token()
599                .await
600                .map(|token| DcRegion::from_credential(&token))
601                .unwrap_or(DcRegion::Ap),
602        }
603    }
604
605    fn create_ws_request(
606        &self,
607        url: &str,
608        dc_region: DcRegion,
609    ) -> tokio_tungstenite::tungstenite::Result<Request<()>> {
610        let mut request = url.into_client_request()?;
611        request.headers_mut().append(
612            header::ACCEPT_LANGUAGE,
613            HeaderValue::from_str(self.language.as_str()).unwrap(),
614        );
615        for (key, value) in &self.custom_headers {
616            if let (Ok(name), Ok(val)) = (
617                HeaderName::from_bytes(key.as_bytes()),
618                HeaderValue::from_str(value),
619            ) {
620                request.headers_mut().append(name, val);
621            }
622        }
623        // Route the upgrade to the data center matching the credential's
624        // region, unless the caller already set the header via a custom
625        // header.
626        if !self
627            .custom_headers
628            .keys()
629            .any(|key| key.eq_ignore_ascii_case(DC_REGION_HEADER))
630        {
631            request.headers_mut().append(
632                HeaderName::from_static(DC_REGION_HEADER),
633                HeaderValue::from_static(dc_region.as_str()),
634            );
635        }
636        Ok(request)
637    }
638
639    pub(crate) async fn create_quote_ws_request(
640        &self,
641    ) -> (&str, tokio_tungstenite::tungstenite::Result<Request<()>>) {
642        let dc_region = self.auth_dc_region().await;
643        match self.quote_ws_url.as_deref() {
644            Some(url) => (url, self.create_ws_request(url, dc_region)),
645            None => {
646                let url = if is_cn().await {
647                    DEFAULT_QUOTE_WS_URL_CN
648                } else {
649                    DEFAULT_QUOTE_WS_URL
650                };
651                (url, self.create_ws_request(url, dc_region))
652            }
653        }
654    }
655
656    pub(crate) async fn create_trade_ws_request(
657        &self,
658    ) -> (&str, tokio_tungstenite::tungstenite::Result<Request<()>>) {
659        let dc_region = self.auth_dc_region().await;
660        match self.trade_ws_url.as_deref() {
661            Some(url) => (url, self.create_ws_request(url, dc_region)),
662            None => {
663                let url = if is_cn().await {
664                    DEFAULT_TRADE_WS_URL_CN
665                } else {
666                    DEFAULT_TRADE_WS_URL
667                };
668                (url, self.create_ws_request(url, dc_region))
669            }
670        }
671    }
672
673    /// Specifies the path of the log file
674    ///
675    /// Default: `None`
676    pub fn log_path(mut self, path: impl Into<PathBuf>) -> Self {
677        self.log_path = Some(path.into());
678        self
679    }
680
681    /// Add a custom header to every HTTP request and WebSocket upgrade request.
682    #[must_use]
683    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
684        self.custom_headers.insert(key.into(), value.into());
685        self
686    }
687
688    /// Override the data-center region for every HTTP and WebSocket request by
689    /// setting the [`DC_REGION_HEADER`](crate::DC_REGION_HEADER) explicitly.
690    ///
691    /// This is rarely needed: the region is otherwise derived automatically
692    /// from the auth credentials' prefix (`us_`/`ap_`). Use this only to
693    /// force a specific data center regardless of the credential.
694    #[must_use]
695    pub fn dc_region(self, region: DcRegion) -> Self {
696        self.header(DC_REGION_HEADER, region.as_str())
697    }
698
699    /// Set the HTTP endpoint URL in place.
700    pub fn set_http_url(&mut self, url: impl Into<String>) {
701        self.http_url = Some(url.into());
702    }
703
704    /// Set the quote websocket endpoint URL in place.
705    pub fn set_quote_ws_url(&mut self, url: impl Into<String>) {
706        self.quote_ws_url = Some(url.into());
707    }
708
709    /// Set the trade websocket endpoint URL in place.
710    pub fn set_trade_ws_url(&mut self, url: impl Into<String>) {
711        self.trade_ws_url = Some(url.into());
712    }
713
714    /// Set the language in place.
715    pub fn set_language(&mut self, language: Language) {
716        self.language = language;
717    }
718
719    /// Enable overnight quote in place.
720    pub fn set_enable_overnight(&mut self) {
721        self.enable_overnight = Some(true);
722    }
723
724    /// Set the push candlestick mode in place.
725    pub fn set_push_candlestick_mode(&mut self, mode: PushCandlestickMode) {
726        self.push_candlestick_mode = Some(mode);
727    }
728
729    /// Disable printing quote packages in place.
730    pub fn set_dont_print_quote_packages(&mut self) {
731        self.enable_print_quote_packages = false;
732    }
733
734    /// Enable paper trading mode in place.
735    ///
736    /// See [`Config::enable_papertrading`] for full semantics.
737    pub fn set_enable_papertrading(&mut self) {
738        self.enable_papertrading = true;
739    }
740
741    /// Set the quote transport in place.
742    ///
743    /// See [`Config::quote_transport`] for full semantics.
744    pub fn set_quote_transport(&mut self, quote_transport: QuoteTransport) {
745        self.quote_transport = quote_transport;
746    }
747
748    /// Set the log path in place.
749    pub fn set_log_path(&mut self, path: impl Into<PathBuf>) {
750        self.log_path = Some(path.into());
751    }
752
753    pub(crate) fn create_log_subscriber(
754        &self,
755        path: impl AsRef<Path>,
756    ) -> Arc<dyn Subscriber + Send + Sync> {
757        fn internal_create_log_subscriber(
758            config: &Config,
759            path: impl AsRef<Path>,
760        ) -> Option<Arc<dyn Subscriber + Send + Sync>> {
761            let log_path = config.log_path.as_ref()?;
762            let appender = RollingFileAppender::builder()
763                .rotation(Rotation::DAILY)
764                .filename_suffix("log")
765                .build(log_path.join(path))
766                .ok()?;
767            Some(Arc::new(
768                tracing_subscriber::fmt()
769                    .with_writer(appender)
770                    .with_ansi(false)
771                    .finish()
772                    .with(Targets::new().with_targets([("longport", Level::INFO)])),
773            ))
774        }
775
776        internal_create_log_subscriber(self, path).unwrap_or_else(|| Arc::new(NoSubscriber::new()))
777    }
778}
779
780#[cfg(test)]
781mod tests {
782    use super::*;
783
784    #[test]
785    fn test_config_from_apikey() {
786        let config = Config::from_apikey("app-key", "app-secret", "token");
787        assert_eq!(config.language, Language::EN);
788        match &config.auth {
789            AuthMode::ApiKey {
790                app_key,
791                app_secret,
792                access_token,
793            } => {
794                assert_eq!(app_key, "app-key");
795                assert_eq!(app_secret, "app-secret");
796                assert_eq!(access_token, "token");
797            }
798            _ => panic!("Expected ApiKey auth mode"),
799        }
800    }
801
802    #[test]
803    fn test_config_default_values() {
804        let config = Config::from_apikey("key", "secret", "token");
805
806        // Fields not controlled by environment variables
807        assert_eq!(config.enable_overnight, None);
808        assert_eq!(config.push_candlestick_mode, None);
809        assert!(config.enable_print_quote_packages);
810    }
811
812    #[test]
813    fn test_enable_papertrading_builder() {
814        let config = Config::from_apikey("key", "secret", "token").enable_papertrading();
815        assert!(config.enable_papertrading);
816    }
817
818    #[test]
819    fn test_enable_papertrading_setter() {
820        let mut config = Config::from_apikey("key", "secret", "token");
821        config.set_enable_papertrading();
822        assert!(config.enable_papertrading);
823    }
824}