fugle-marketdata-core 0.6.0

Internal kernel for the Fugle market data SDK. End users should depend on `fugle-marketdata` instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! REST client for Fugle marketdata API

use super::auth::Auth;
use super::retry::{self, RetryPolicy};
use crate::errors::MarketDataError;
use crate::tls::{build_rustls_config, TlsConfig};

/// Main REST client with connection pooling via ureq Agent
///
/// The RestClient uses ureq's Agent for automatic connection pooling and reuse.
/// Cloning the client is cheap - it shares the same connection pool.
///
/// # Connection Pooling
///
/// The underlying ureq Agent maintains a connection pool that:
/// - Reuses TCP connections across multiple requests
/// - Reduces connection overhead for subsequent requests
/// - Automatically handles connection lifecycle
///
/// # Thread Safety
///
/// The RestClient is NOT Send/Sync due to ureq::Agent implementation.
/// For multi-threaded usage, create a separate client per thread.
pub struct RestClient {
    agent: ureq::Agent,
    auth: Auth,
    base_url: String,
    /// Optional retry policy. `None` (default) means each request is
    /// attempted exactly once and any error propagates to the caller.
    retry_policy: Option<RetryPolicy>,
}

impl RestClient {
    /// Create a new REST client with authentication
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// ```
    pub fn new(auth: Auth) -> Self {
        // Building a default rustls config can only realistically fail if the
        // crypto provider installs unexpectedly differently (extremely rare).
        // Panic at construction so consumers get a clear failure mode instead
        // of an opaque error on first request.
        Self::with_tls(auth, TlsConfig::default())
            .expect("default rustls config should build on supported platforms")
    }

    /// Create a REST client with custom TLS configuration (custom root CA
    /// or "accept invalid certs"). Prefer `new()` for production usage
    /// against public Fugle endpoints.
    ///
    /// Returns a `ConfigError` if the PEM in `tls.root_cert_pem` is malformed.
    ///
    /// # Errors
    /// Returns [`MarketDataError`] on transport, deserialization, validation,
    /// or non-2xx API failures.
    pub fn with_tls(auth: Auth, tls: TlsConfig) -> Result<Self, MarketDataError> {
        let tls_config = build_rustls_config(&tls)?;
        let builder = ureq::AgentBuilder::new()
            .timeout_read(std::time::Duration::from_secs(30))
            .timeout_write(std::time::Duration::from_secs(30))
            .tls_config(tls_config);

        Ok(Self {
            agent: builder.build(),
            auth,
            base_url: crate::urls::REST_BASE.to_string(),
            retry_policy: None,
        })
    }

    /// Enable transparent retry of failed requests.
    ///
    /// By default the client does not retry — observability use cases
    /// need real failures visible. With a [`RetryPolicy`] installed,
    /// errors for which [`MarketDataError::is_retryable`] returns `true`
    /// (HTTP 429, HTTP 5xx, transport timeouts and connection errors)
    /// are retried with exponential backoff plus jitter, up to
    /// `max_attempts` total attempts. Other errors propagate immediately.
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{Auth, RestClient, RetryPolicy};
    ///
    /// let client = RestClient::new(Auth::SdkToken("t".into()))
    ///     .with_retry(RetryPolicy::conservative());
    /// ```
    pub fn with_retry(mut self, policy: RetryPolicy) -> Self {
        self.retry_policy = Some(policy);
        self
    }

    /// Execute a prepared `ureq::Request`, applying any installed
    /// [`RetryPolicy`].
    ///
    /// Builders inside this crate route their `.call()` through here so
    /// retry semantics remain centralized.
    pub(crate) fn execute(
        &self,
        request: ureq::Request,
    ) -> Result<ureq::Response, MarketDataError> {
        match self.retry_policy {
            Some(policy) => retry::run(&policy, || {
                let req = request.clone();
                req.call().map_err(MarketDataError::from)
            }),
            None => request.call().map_err(MarketDataError::from),
        }
    }

    /// Override the base URL (useful for testing or custom endpoints)
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()))
    ///     .base_url("https://custom.api.example.com");
    /// ```
    pub fn base_url(mut self, url: &str) -> Self {
        self.base_url = url.to_string();
        self
    }

    /// Access stock-related endpoints
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let stock_client = client.stock();
    /// ```
    pub fn stock(&self) -> StockClient<'_> {
        StockClient { client: self }
    }

    /// Access FutOpt (futures and options) endpoints
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let futopt_client = client.futopt();
    /// ```
    pub fn futopt(&self) -> super::futopt::FutOptClient<'_> {
        super::futopt::FutOptClient { client: self }
    }

    /// Internal helper to get the agent
    pub(crate) fn agent(&self) -> &ureq::Agent {
        &self.agent
    }

    /// Internal helper to get the auth
    pub(crate) fn auth(&self) -> &Auth {
        &self.auth
    }

    /// Internal helper to get the base URL
    pub(crate) fn get_base_url(&self) -> &str {
        &self.base_url
    }
}

impl Clone for RestClient {
    /// Clone the RestClient, sharing the same connection pool
    ///
    /// Cloning is cheap because ureq::Agent internally uses Arc for connection pool sharing.
    /// Multiple cloned clients will share the same connection pool.
    fn clone(&self) -> Self {
        Self {
            agent: self.agent.clone(),
            auth: self.auth.clone(),
            base_url: self.base_url.clone(),
            retry_policy: self.retry_policy,
        }
    }
}

/// Stock-related endpoints client
pub struct StockClient<'a> {
    client: &'a RestClient,
}

impl<'a> StockClient<'a> {
    /// Access intraday (real-time) endpoints
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let intraday = client.stock().intraday();
    /// ```
    pub fn intraday(&self) -> IntradayClient<'a> {
        IntradayClient {
            client: self.client,
        }
    }

    /// Access historical data endpoints
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let historical = client.stock().historical();
    /// ```
    pub fn historical(&self) -> HistoricalClient<'a> {
        HistoricalClient {
            client: self.client,
        }
    }

    /// Access technical indicator endpoints
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let technical = client.stock().technical();
    /// ```
    pub fn technical(&self) -> crate::rest::stock::technical::TechnicalClient<'a> {
        crate::rest::stock::technical::TechnicalClient::new(self.client)
    }

    /// Access snapshot endpoints for market-wide data
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let snapshot = client.stock().snapshot();
    /// ```
    pub fn snapshot(&self) -> crate::rest::stock::snapshot::SnapshotClient<'a> {
        crate::rest::stock::snapshot::SnapshotClient::new(self.client)
    }

    /// Access corporate actions endpoints (capital changes, dividends, IPO listings)
    ///
    /// # Example
    /// ```
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let corporate_actions = client.stock().corporate_actions();
    /// ```
    pub fn corporate_actions(&self) -> CorporateActionsClient<'a> {
        CorporateActionsClient {
            client: self.client,
        }
    }
}

/// Corporate actions endpoints client
pub struct CorporateActionsClient<'a> {
    client: &'a RestClient,
}

impl<'a> CorporateActionsClient<'a> {
    /// Get capital structure changes
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let changes = client.stock().corporate_actions().capital_changes().send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn capital_changes(&self) -> crate::rest::stock::corporate_actions::CapitalChangesRequestBuilder<'_> {
        crate::rest::stock::corporate_actions::CapitalChangesRequestBuilder::new(self.client)
    }

    /// Get dividend announcements
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let dividends = client.stock().corporate_actions().dividends().send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn dividends(&self) -> crate::rest::stock::corporate_actions::DividendsRequestBuilder<'_> {
        crate::rest::stock::corporate_actions::DividendsRequestBuilder::new(self.client)
    }

    /// Get IPO listing applicants
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let applicants = client.stock().corporate_actions().listing_applicants().send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn listing_applicants(&self) -> crate::rest::stock::corporate_actions::ListingApplicantsRequestBuilder<'_> {
        crate::rest::stock::corporate_actions::ListingApplicantsRequestBuilder::new(self.client)
    }
}

/// Historical data endpoints client
pub struct HistoricalClient<'a> {
    client: &'a RestClient,
}

impl<'a> HistoricalClient<'a> {
    /// Get historical candles for a symbol
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let candles = client.stock().historical().candles()
    ///     .symbol("2330")
    ///     .from("2024-01-01")
    ///     .to("2024-01-31")
    ///     .send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn candles(&self) -> crate::rest::stock::historical::HistoricalCandlesRequestBuilder<'_> {
        crate::rest::stock::historical::HistoricalCandlesRequestBuilder::new(self.client)
    }

    /// Get historical stats for a symbol
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let stats = client.stock().historical().stats()
    ///     .symbol("2330")
    ///     .send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn stats(&self) -> crate::rest::stock::historical::StatsRequestBuilder<'_> {
        crate::rest::stock::historical::StatsRequestBuilder::new(self.client)
    }
}

/// Intraday (real-time) endpoints client
pub struct IntradayClient<'a> {
    client: &'a RestClient,
}

impl<'a> IntradayClient<'a> {
    /// Get intraday quote for a symbol
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let quote = client.stock().intraday().quote().symbol("2330").send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn quote(&self) -> crate::rest::stock::intraday::QuoteRequestBuilder<'_> {
        crate::rest::stock::intraday::QuoteRequestBuilder::new(self.client)
    }

    /// Get intraday ticker info for a symbol
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let ticker = client.stock().intraday().ticker().symbol("2330").send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn ticker(&self) -> crate::rest::stock::intraday::TickerRequestBuilder<'_> {
        crate::rest::stock::intraday::TickerRequestBuilder::new(self.client)
    }

    /// Get intraday tickers (batch list) for a security type
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let tickers = client.stock().intraday().tickers().typ("EQUITY").send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn tickers(&self) -> crate::rest::stock::intraday::TickersRequestBuilder<'_> {
        crate::rest::stock::intraday::TickersRequestBuilder::new(self.client)
    }

    /// Get intraday candles for a symbol
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let candles = client.stock().intraday().candles().symbol("2330").timeframe("5").send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn candles(&self) -> crate::rest::stock::intraday::CandlesRequestBuilder<'_> {
        crate::rest::stock::intraday::CandlesRequestBuilder::new(self.client)
    }

    /// Get intraday trades for a symbol
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let trades = client.stock().intraday().trades().symbol("2330").send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn trades(&self) -> crate::rest::stock::intraday::TradesRequestBuilder<'_> {
        crate::rest::stock::intraday::TradesRequestBuilder::new(self.client)
    }

    /// Get intraday volumes for a symbol
    ///
    /// # Example
    /// ```no_run
    /// use marketdata_core::{RestClient, Auth};
    ///
    /// let client = RestClient::new(Auth::SdkToken("my-token".to_string()));
    /// let volumes = client.stock().intraday().volumes().symbol("2330").send()?;
    /// # Ok::<(), marketdata_core::MarketDataError>(())
    /// ```
    pub fn volumes(&self) -> crate::rest::stock::intraday::VolumesRequestBuilder<'_> {
        crate::rest::stock::intraday::VolumesRequestBuilder::new(self.client)
    }
}

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

    #[test]
    fn test_rest_client_creation() {
        let client = RestClient::new(Auth::SdkToken("test-token".to_string()));
        assert_eq!(client.get_base_url(), "https://api.fugle.tw/marketdata/v1.0");
    }

    #[test]
    fn test_rest_client_custom_base_url() {
        let client = RestClient::new(Auth::SdkToken("test-token".to_string()))
            .base_url("https://custom.example.com");
        assert_eq!(client.get_base_url(), "https://custom.example.com");
    }

    #[test]
    fn test_stock_client_creation() {
        let client = RestClient::new(Auth::ApiKey("test-key".to_string()));
        let stock_client = client.stock();
        assert_eq!(stock_client.client.get_base_url(), "https://api.fugle.tw/marketdata/v1.0");
    }

    #[test]
    fn test_intraday_client_creation() {
        let client = RestClient::new(Auth::BearerToken("test-bearer".to_string()));
        let intraday = client.stock().intraday();
        assert_eq!(intraday.client.get_base_url(), "https://api.fugle.tw/marketdata/v1.0");
    }

    #[test]
    fn test_chained_client_access() {
        let client = RestClient::new(Auth::SdkToken("test".to_string()));
        let _intraday = client.stock().intraday();
        // Compilation success proves the chaining works
    }

    #[test]
    fn test_auth_types() {
        // Test all three auth types
        let _client1 = RestClient::new(Auth::ApiKey("key".to_string()));
        let _client2 = RestClient::new(Auth::BearerToken("token".to_string()));
        let _client3 = RestClient::new(Auth::SdkToken("sdk".to_string()));
    }

    #[test]
    fn test_client_clone() {
        let client = RestClient::new(Auth::SdkToken("test".to_string()));
        let cloned = client.clone();

        // Cloned client should have same base URL and auth
        assert_eq!(client.get_base_url(), cloned.get_base_url());
    }

    #[test]
    fn test_connection_pool_sharing() {
        // Create client with connection pool
        let client = RestClient::new(Auth::SdkToken("test".to_string()));

        // Clone shares the same connection pool (via Arc in ureq::Agent)
        let cloned = client.clone();

        // Both clients should be usable
        let _stock1 = client.stock().intraday();
        let _stock2 = cloned.stock().intraday();

        // Compilation and execution success proves connection pool works
    }

    #[test]
    fn test_custom_base_url_preserved_in_clone() {
        let client = RestClient::new(Auth::SdkToken("test".to_string()))
            .base_url("https://custom.example.com");

        let cloned = client.clone();
        assert_eq!(cloned.get_base_url(), "https://custom.example.com");
    }

    #[test]
    fn test_futopt_client_creation() {
        let client = RestClient::new(Auth::SdkToken("test".to_string()));
        let futopt = client.futopt();
        assert_eq!(futopt.client.get_base_url(), "https://api.fugle.tw/marketdata/v1.0");
    }

    #[test]
    fn test_futopt_intraday_client_creation() {
        let client = RestClient::new(Auth::SdkToken("test".to_string()));
        let intraday = client.futopt().intraday();
        assert_eq!(intraday.client.get_base_url(), "https://api.fugle.tw/marketdata/v1.0");
    }

    #[test]
    fn test_futopt_chained_client_access() {
        let client = RestClient::new(Auth::SdkToken("test".to_string()));
        let _intraday = client.futopt().intraday();
        // Compilation success proves the chaining works
    }

    #[test]
    fn test_both_stock_and_futopt() {
        let client = RestClient::new(Auth::SdkToken("test".to_string()));

        // Both stock and futopt should be accessible from the same client
        let _stock = client.stock().intraday();
        let _futopt = client.futopt().intraday();
    }

    #[test]
    fn test_corporate_actions_client_creation() {
        let client = RestClient::new(Auth::SdkToken("test".to_string()));
        let corporate_actions = client.stock().corporate_actions();
        assert_eq!(corporate_actions.client.get_base_url(), "https://api.fugle.tw/marketdata/v1.0");
    }

    #[test]
    fn test_corporate_actions_chained_access() {
        let client = RestClient::new(Auth::SdkToken("test".to_string()));
        // Test that all corporate actions endpoints are accessible
        let _capital_changes = client.stock().corporate_actions().capital_changes();
        let _dividends = client.stock().corporate_actions().dividends();
        let _listing_applicants = client.stock().corporate_actions().listing_applicants();
    }
}