Skip to main content

nautilus_betfair/
config.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Configuration structures for the Betfair adapter.
17
18use std::{any::Any, fmt::Debug};
19
20use nautilus_common::{config::check_unique_values, factories::ClientConfig};
21#[cfg(test)]
22use nautilus_core::string::secret::REDACTED;
23use nautilus_core::string::secret::SecretString;
24use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
25use nautilus_model::{
26    identifiers::AccountId,
27    types::{Currency, Money},
28};
29use rust_decimal::Decimal;
30use serde::{Deserialize, Serialize};
31
32use crate::{
33    common::{
34        credential::{BetfairCredential, CredentialError},
35        parse::parse_betfair_timestamp,
36    },
37    provider::NavigationFilter,
38    stream::config::BetfairStreamConfig,
39};
40
41fn parse_currency(code: &str) -> anyhow::Result<Currency> {
42    code.parse::<Currency>()
43        .map_err(|_| anyhow::anyhow!("Invalid account currency code: {code}"))
44}
45
46fn make_min_notional(value: Option<Decimal>, currency: Currency) -> anyhow::Result<Option<Money>> {
47    value
48        .map(|amount| Money::from_decimal(amount, currency))
49        .transpose()
50        .map_err(Into::into)
51}
52
53fn validate_market_start_time(label: &str, value: &Option<String>) -> anyhow::Result<()> {
54    if let Some(value) = value {
55        parse_betfair_timestamp(value)
56            .map(|_| ())
57            .map_err(|e| anyhow::anyhow!("Invalid {label} '{value}': {e}"))?;
58    }
59
60    Ok(())
61}
62
63fn resolve_credential(
64    username: Option<SecretString>,
65    password: Option<SecretString>,
66    app_key: Option<SecretString>,
67    certs_dir: Option<String>,
68) -> anyhow::Result<BetfairCredential> {
69    match BetfairCredential::resolve(
70        username.map(SecretString::into_inner),
71        password.map(SecretString::into_inner),
72        app_key.map(SecretString::into_inner),
73    ) {
74        Ok(Some(credential)) => Ok(match certs_dir {
75            Some(dir) => credential.with_certs_dir(dir),
76            None => credential,
77        }),
78        Ok(None) => anyhow::bail!("Missing Betfair credentials in config and environment"),
79        Err(e) => Err(match e {
80            CredentialError::MissingPassword => anyhow::anyhow!(
81                "Invalid Betfair credentials: username provided but password is missing",
82            ),
83            CredentialError::MissingUsername => anyhow::anyhow!(
84                "Invalid Betfair credentials: password or app key provided but username is missing",
85            ),
86            CredentialError::MissingAppKey => {
87                anyhow::anyhow!("Invalid Betfair credentials: app key is missing")
88            }
89        }),
90    }
91}
92
93fn build_stream_config(
94    stream_host: &Option<String>,
95    stream_port: &Option<u16>,
96    stream_heartbeat_secs: Option<u64>,
97    stream_heartbeat_timeout_secs: Option<u64>,
98    stream_reconnect_delay_initial_ms: u64,
99    stream_reconnect_delay_max_ms: u64,
100    stream_use_tls: bool,
101) -> BetfairStreamConfig {
102    let defaults = BetfairStreamConfig::default();
103
104    BetfairStreamConfig {
105        host: stream_host.clone().unwrap_or(defaults.host),
106        port: stream_port.unwrap_or(defaults.port),
107        heartbeat_secs: stream_heartbeat_secs,
108        heartbeat_timeout_secs: stream_heartbeat_timeout_secs,
109        reconnect_delay_initial_ms: stream_reconnect_delay_initial_ms,
110        reconnect_delay_max_ms: stream_reconnect_delay_max_ms,
111        use_tls: stream_use_tls,
112    }
113}
114
115/// Configuration for the Betfair live data client.
116#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
117#[serde(default, deny_unknown_fields)]
118#[cfg_attr(
119    feature = "python",
120    pyo3::pyclass(module = "nautilus_trader.adapters.betfair", from_py_object)
121)]
122#[cfg_attr(
123    feature = "python",
124    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.betfair")
125)]
126pub struct BetfairDataClientConfig {
127    /// Account currency code.
128    #[builder(default = "GBP".to_string())]
129    pub account_currency: String,
130    /// Optional Betfair username.
131    pub username: Option<SecretString>,
132    /// Optional Betfair password.
133    pub password: Option<SecretString>,
134    /// Optional Betfair application key.
135    pub app_key: Option<SecretString>,
136    /// Optional proxy URL for HTTP requests.
137    pub proxy_url: Option<SecretString>,
138    /// General HTTP request rate limit per second.
139    #[builder(default = 5)]
140    pub request_rate_per_second: u32,
141    /// Optional default minimum notional in `account_currency`.
142    pub default_min_notional: Option<Decimal>,
143    /// Optional event type ID filter.
144    pub event_type_ids: Option<Vec<String>>,
145    /// Optional event type name filter.
146    pub event_type_names: Option<Vec<String>>,
147    /// Optional event ID filter.
148    pub event_ids: Option<Vec<String>>,
149    /// Optional country code filter.
150    pub country_codes: Option<Vec<String>>,
151    /// Optional market type filter.
152    pub market_types: Option<Vec<String>>,
153    /// Optional market ID filter.
154    pub market_ids: Option<Vec<String>>,
155    /// Optional lower bound for market start time.
156    pub min_market_start_time: Option<String>,
157    /// Optional upper bound for market start time.
158    pub max_market_start_time: Option<String>,
159    /// Optional override for stream host.
160    pub stream_host: Option<String>,
161    /// Optional override for stream port.
162    pub stream_port: Option<u16>,
163    /// Optional interval between outbound stream heartbeat messages in seconds.
164    pub stream_heartbeat_secs: Option<u64>,
165    /// Optional dead-peer timeout override in seconds.
166    pub stream_heartbeat_timeout_secs: Option<u64>,
167    /// Initial reconnection backoff in milliseconds.
168    #[builder(default = 2_000)]
169    pub stream_reconnect_delay_initial_ms: u64,
170    /// Maximum reconnection backoff in milliseconds.
171    #[builder(default = 30_000)]
172    pub stream_reconnect_delay_max_ms: u64,
173    /// Whether to use TLS for the stream connection.
174    #[builder(default = true)]
175    pub stream_use_tls: bool,
176    /// Stream conflation setting in milliseconds. When set, Betfair batches
177    /// stream updates for this interval. `None` uses Betfair defaults.
178    pub stream_conflate_ms: Option<u64>,
179    /// Delay in seconds before sending the initial subscription message after connecting.
180    #[builder(default = 3)]
181    pub subscription_delay_secs: u64,
182    /// Subscribe to the race stream for Total Performance Data (TPD).
183    #[builder(default)]
184    pub subscribe_race_data: bool,
185    /// Subscribe to the sports data stream for cricket match updates.
186    #[builder(default)]
187    pub subscribe_cricket_data: bool,
188    /// Maximum time to wait for an initial or recovery market image in seconds.
189    /// Set to 0 to disable.
190    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
191    pub book_snapshot_timeout_secs: u64,
192    /// Directory containing the client certificate and private key for certificate login.
193    pub certs_dir: Option<String>,
194}
195
196#[cfg(feature = "python")]
197nautilus_core::impl_pyo3_config_getters!(BetfairDataClientConfig {
198    account_currency: String,
199    request_rate_per_second: u32,
200    default_min_notional: Option<Decimal>,
201    event_type_ids: Option<Vec<String>>,
202    event_type_names: Option<Vec<String>>,
203    event_ids: Option<Vec<String>>,
204    country_codes: Option<Vec<String>>,
205    market_types: Option<Vec<String>>,
206    market_ids: Option<Vec<String>>,
207    min_market_start_time: Option<String>,
208    max_market_start_time: Option<String>,
209    stream_host: Option<String>,
210    stream_port: Option<u16>,
211    stream_heartbeat_secs: Option<u64>,
212    stream_heartbeat_timeout_secs: Option<u64>,
213    stream_reconnect_delay_initial_ms: u64,
214    stream_reconnect_delay_max_ms: u64,
215    stream_use_tls: bool,
216    stream_conflate_ms: Option<u64>,
217    subscription_delay_secs: u64,
218    subscribe_race_data: bool,
219    subscribe_cricket_data: bool,
220    book_snapshot_timeout_secs: u64,
221    certs_dir: Option<String>,
222});
223
224impl Default for BetfairDataClientConfig {
225    fn default() -> Self {
226        Self::builder().build()
227    }
228}
229
230impl ClientConfig for BetfairDataClientConfig {
231    fn as_any(&self) -> &dyn Any {
232        self
233    }
234}
235
236impl BetfairDataClientConfig {
237    /// Returns the configured credentials or resolves them from the environment.
238    ///
239    /// # Errors
240    ///
241    /// Returns an error if credentials are incomplete or unavailable.
242    pub fn credential(&self) -> anyhow::Result<BetfairCredential> {
243        resolve_credential(
244            self.username.clone(),
245            self.password.clone(),
246            self.app_key.clone(),
247            self.certs_dir.clone(),
248        )
249    }
250
251    /// Returns the configured account currency.
252    ///
253    /// # Errors
254    ///
255    /// Returns an error if the currency code is invalid.
256    pub fn currency(&self) -> anyhow::Result<Currency> {
257        parse_currency(&self.account_currency)
258    }
259
260    /// Returns the default instrument minimum notional.
261    ///
262    /// # Errors
263    ///
264    /// Returns an error if the account currency code is invalid.
265    pub fn min_notional(&self) -> anyhow::Result<Option<Money>> {
266        let currency = self.currency()?;
267        make_min_notional(self.default_min_notional, currency)
268    }
269
270    /// Returns the navigation filter for instrument loading.
271    #[must_use]
272    pub fn navigation_filter(&self) -> NavigationFilter {
273        NavigationFilter {
274            event_type_ids: self.event_type_ids.clone(),
275            event_type_names: self.event_type_names.clone(),
276            event_ids: self.event_ids.clone(),
277            country_codes: self.country_codes.clone(),
278            market_types: self.market_types.clone(),
279            market_ids: self.market_ids.clone(),
280            min_market_start_time: self.min_market_start_time.clone(),
281            max_market_start_time: self.max_market_start_time.clone(),
282        }
283    }
284
285    /// Returns the stream configuration.
286    #[must_use]
287    pub fn stream_config(&self) -> BetfairStreamConfig {
288        build_stream_config(
289            &self.stream_host,
290            &self.stream_port,
291            self.stream_heartbeat_secs,
292            self.stream_heartbeat_timeout_secs,
293            self.stream_reconnect_delay_initial_ms,
294            self.stream_reconnect_delay_max_ms,
295            self.stream_use_tls,
296        )
297    }
298
299    /// Validates the configuration.
300    ///
301    /// # Errors
302    ///
303    /// Returns an error if any configured value is invalid.
304    pub fn validate(&self) -> anyhow::Result<()> {
305        if let Some(values) = &self.event_type_ids {
306            check_unique_values("event_type_ids", values)?;
307        }
308
309        if let Some(values) = &self.event_type_names {
310            check_unique_values("event_type_names", values)?;
311        }
312
313        if let Some(values) = &self.event_ids {
314            check_unique_values("event_ids", values)?;
315        }
316
317        if let Some(values) = &self.country_codes {
318            check_unique_values("country_codes", values)?;
319        }
320
321        if let Some(values) = &self.market_types {
322            check_unique_values("market_types", values)?;
323        }
324
325        if let Some(values) = &self.market_ids {
326            check_unique_values("market_ids", values)?;
327        }
328
329        let _ = self.currency()?;
330        validate_market_start_time("min_market_start_time", &self.min_market_start_time)?;
331        validate_market_start_time("max_market_start_time", &self.max_market_start_time)?;
332
333        if self.request_rate_per_second == 0 {
334            anyhow::bail!("request_rate_per_second must be greater than zero");
335        }
336
337        self.stream_config().validate()?;
338
339        Ok(())
340    }
341}
342
343/// Configuration for the Betfair live execution client.
344#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
345#[serde(default, deny_unknown_fields)]
346#[cfg_attr(
347    feature = "python",
348    pyo3::pyclass(module = "nautilus_trader.adapters.betfair", from_py_object)
349)]
350#[cfg_attr(
351    feature = "python",
352    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.betfair")
353)]
354pub struct BetfairExecutionClientConfig {
355    /// Account ID for the client core.
356    #[builder(default = AccountId::from("BETFAIR-001"))]
357    pub account_id: AccountId,
358    /// Account currency code.
359    #[builder(default = "GBP".to_string())]
360    pub account_currency: String,
361    /// Optional Betfair username.
362    pub username: Option<SecretString>,
363    /// Optional Betfair password.
364    pub password: Option<SecretString>,
365    /// Optional Betfair application key.
366    pub app_key: Option<SecretString>,
367    /// Optional proxy URL for HTTP requests.
368    pub proxy_url: Option<SecretString>,
369    /// General HTTP request rate limit per second.
370    #[builder(default = 5)]
371    pub request_rate_per_second: u32,
372    /// Order HTTP request rate limit per second.
373    #[builder(default = 20)]
374    pub order_request_rate_per_second: u32,
375    /// Optional override for stream host.
376    pub stream_host: Option<String>,
377    /// Optional override for stream port.
378    pub stream_port: Option<u16>,
379    /// Optional interval between outbound stream heartbeat messages in seconds.
380    pub stream_heartbeat_secs: Option<u64>,
381    /// Optional dead-peer timeout override in seconds.
382    pub stream_heartbeat_timeout_secs: Option<u64>,
383    /// Initial reconnection backoff in milliseconds.
384    #[builder(default = 2_000)]
385    pub stream_reconnect_delay_initial_ms: u64,
386    /// Maximum reconnection backoff in milliseconds.
387    #[builder(default = 30_000)]
388    pub stream_reconnect_delay_max_ms: u64,
389    /// Whether to use TLS for the stream connection.
390    #[builder(default = true)]
391    pub stream_use_tls: bool,
392    /// Market IDs to filter on the order stream. When set, OCM updates for
393    /// markets not in this list are skipped. `None` processes all markets.
394    pub stream_market_ids_filter: Option<Vec<String>>,
395    /// When true, silently ignore orders from OCM that are not tracked in the local cache.
396    #[builder(default)]
397    pub ignore_external_orders: bool,
398    /// Whether to poll account state periodically.
399    #[builder(default = true)]
400    pub calculate_account_state: bool,
401    /// Interval in seconds between account state polls.
402    #[builder(default = 300)]
403    pub request_account_state_secs: u64,
404    /// When true, reconciliation only requests orders matching `reconcile_market_ids`.
405    #[builder(default)]
406    pub reconcile_market_ids_only: bool,
407    /// Market IDs to restrict reconciliation to.
408    pub reconcile_market_ids: Option<Vec<String>>,
409    /// When true, attach the latest market version to placeOrders and replaceOrders requests.
410    #[builder(default)]
411    pub use_market_version: bool,
412    /// Lookback window in minutes for the post-reconnect mass-status reconciliation
413    /// that recovers fills which terminated during the disconnect gap. Should
414    /// comfortably exceed the longest expected reconnect duration.
415    #[builder(default = 10)]
416    pub stream_gap_recovery_lookback_mins: u64,
417    /// Directory containing the client certificate and private key for certificate login.
418    pub certs_dir: Option<String>,
419}
420
421#[cfg(feature = "python")]
422nautilus_core::impl_pyo3_config_getters!(BetfairExecutionClientConfig {
423    account_id: AccountId,
424    account_currency: String,
425    request_rate_per_second: u32,
426    order_request_rate_per_second: u32,
427    stream_host: Option<String>,
428    stream_port: Option<u16>,
429    stream_heartbeat_secs: Option<u64>,
430    stream_heartbeat_timeout_secs: Option<u64>,
431    stream_reconnect_delay_initial_ms: u64,
432    stream_reconnect_delay_max_ms: u64,
433    stream_use_tls: bool,
434    stream_market_ids_filter: Option<Vec<String>>,
435    ignore_external_orders: bool,
436    calculate_account_state: bool,
437    request_account_state_secs: u64,
438    reconcile_market_ids_only: bool,
439    reconcile_market_ids: Option<Vec<String>>,
440    use_market_version: bool,
441    stream_gap_recovery_lookback_mins: u64,
442    certs_dir: Option<String>,
443});
444
445impl Default for BetfairExecutionClientConfig {
446    fn default() -> Self {
447        Self::builder().build()
448    }
449}
450
451impl ClientConfig for BetfairExecutionClientConfig {
452    fn as_any(&self) -> &dyn Any {
453        self
454    }
455}
456
457impl BetfairExecutionClientConfig {
458    /// Returns the configured credentials or resolves them from the environment.
459    ///
460    /// # Errors
461    ///
462    /// Returns an error if credentials are incomplete or unavailable.
463    pub fn credential(&self) -> anyhow::Result<BetfairCredential> {
464        resolve_credential(
465            self.username.clone(),
466            self.password.clone(),
467            self.app_key.clone(),
468            self.certs_dir.clone(),
469        )
470    }
471
472    /// Returns the configured account currency.
473    ///
474    /// # Errors
475    ///
476    /// Returns an error if the currency code is invalid.
477    pub fn currency(&self) -> anyhow::Result<Currency> {
478        parse_currency(&self.account_currency)
479    }
480
481    /// Returns the stream configuration.
482    #[must_use]
483    pub fn stream_config(&self) -> BetfairStreamConfig {
484        build_stream_config(
485            &self.stream_host,
486            &self.stream_port,
487            self.stream_heartbeat_secs,
488            self.stream_heartbeat_timeout_secs,
489            self.stream_reconnect_delay_initial_ms,
490            self.stream_reconnect_delay_max_ms,
491            self.stream_use_tls,
492        )
493    }
494
495    /// Validates the configuration.
496    ///
497    /// # Errors
498    ///
499    /// Returns an error if any configured value is invalid.
500    pub fn validate(&self) -> anyhow::Result<()> {
501        if let Some(values) = &self.stream_market_ids_filter {
502            check_unique_values("stream_market_ids_filter", values)?;
503        }
504
505        if let Some(values) = &self.reconcile_market_ids {
506            check_unique_values("reconcile_market_ids", values)?;
507        }
508
509        let _ = self.currency()?;
510
511        if self.request_rate_per_second == 0 {
512            anyhow::bail!("request_rate_per_second must be greater than zero");
513        }
514
515        if self.order_request_rate_per_second == 0 {
516            anyhow::bail!("order_request_rate_per_second must be greater than zero");
517        }
518
519        self.stream_config().validate()?;
520
521        Ok(())
522    }
523}
524
525#[cfg(test)]
526mod tests {
527    use nautilus_common::config::ConfigError;
528    use rstest::rstest;
529
530    use super::*;
531
532    #[rstest]
533    #[case("stream_market_ids_filter")]
534    #[case("reconcile_market_ids")]
535    fn test_execution_config_rejects_duplicate_selections(#[case] field: &str) {
536        let mut input = serde_json::to_value(BetfairExecutionClientConfig::default()).unwrap();
537        input[field] = serde_json::json!(["first", "second", "first"]);
538        let config: BetfairExecutionClientConfig = serde_json::from_value(input).unwrap();
539        let original = serde_json::to_value(&config).unwrap();
540        let result = config.validate();
541
542        assert_eq!(
543            result.unwrap_err().downcast_ref::<ConfigError>(),
544            Some(&ConfigError::duplicate(field, None))
545        );
546        assert_eq!(serde_json::to_value(&config).unwrap(), original);
547    }
548
549    #[rstest]
550    #[case("event_type_ids")]
551    #[case("event_type_names")]
552    #[case("event_ids")]
553    #[case("country_codes")]
554    #[case("market_types")]
555    #[case("market_ids")]
556    fn test_data_config_rejects_duplicate_selections(#[case] field: &str) {
557        let mut input = serde_json::to_value(BetfairDataClientConfig::default()).unwrap();
558        input[field] = serde_json::json!(["first", "second", "first"]);
559        let config: BetfairDataClientConfig = serde_json::from_value(input).unwrap();
560        let original = serde_json::to_value(&config).unwrap();
561        let result = config.validate();
562
563        assert_eq!(
564            result.unwrap_err().downcast_ref::<ConfigError>(),
565            Some(&ConfigError::duplicate(field, None))
566        );
567        assert_eq!(serde_json::to_value(&config).unwrap(), original);
568    }
569
570    #[rstest]
571    fn test_config_debug_redacts_credentials() {
572        let data = BetfairDataClientConfig {
573            username: Some("data-username".into()),
574            password: Some("data-password".into()),
575            app_key: Some("data-app-key".into()),
576            proxy_url: Some("http://user:data-proxy@localhost".into()),
577            ..Default::default()
578        };
579        let execution = BetfairExecutionClientConfig {
580            username: Some("exec-username".into()),
581            password: Some("exec-password".into()),
582            app_key: Some("exec-app-key".into()),
583            proxy_url: Some("http://user:exec-proxy@localhost".into()),
584            ..Default::default()
585        };
586
587        let formatted = format!("{data:?} {execution:?}");
588
589        assert_eq!(formatted.matches(REDACTED).count(), 8);
590
591        for secret in [
592            "data-username",
593            "data-password",
594            "data-app-key",
595            "data-proxy",
596            "exec-username",
597            "exec-password",
598            "exec-app-key",
599            "exec-proxy",
600        ] {
601            assert!(!formatted.contains(secret));
602        }
603    }
604
605    #[rstest]
606    #[case(None)]
607    #[case(Some("/betfair/certs".to_string()))]
608    fn test_config_credentials_attach_certs_dir(#[case] certs_dir: Option<String>) {
609        let data = BetfairDataClientConfig::builder()
610            .username("data-user".into())
611            .password("data-password".into())
612            .app_key("data-key".into())
613            .maybe_certs_dir(certs_dir.clone())
614            .build();
615        let execution = BetfairExecutionClientConfig::builder()
616            .username("execution-user".into())
617            .password("execution-password".into())
618            .app_key("execution-key".into())
619            .maybe_certs_dir(certs_dir.clone())
620            .build();
621        let data_credential = data.credential().unwrap();
622        let execution_credential = execution.credential().unwrap();
623
624        assert_eq!(data_credential.username(), "data-user");
625        assert_eq!(data_credential.password(), "data-password");
626        assert_eq!(data_credential.app_key(), "data-key");
627        assert_eq!(data_credential.certs_dir(), certs_dir.as_deref());
628        assert_eq!(execution_credential.username(), "execution-user");
629        assert_eq!(execution_credential.password(), "execution-password");
630        assert_eq!(execution_credential.app_key(), "execution-key");
631        assert_eq!(execution_credential.certs_dir(), certs_dir.as_deref());
632    }
633
634    #[rstest]
635    fn test_data_config_default() {
636        let config = BetfairDataClientConfig::default();
637
638        assert_eq!(config.account_currency, "GBP");
639        assert_eq!(config.request_rate_per_second, 5);
640        assert!(config.market_ids.is_none());
641        assert_eq!(config.stream_heartbeat_secs, None);
642        assert_eq!(config.stream_heartbeat_timeout_secs, None);
643        assert!(config.stream_conflate_ms.is_none());
644        assert_eq!(config.subscription_delay_secs, 3);
645        assert!(!config.subscribe_race_data);
646        assert!(!config.subscribe_cricket_data);
647        assert_eq!(config.book_snapshot_timeout_secs, 10);
648    }
649
650    #[rstest]
651    fn test_data_config_navigation_filter() {
652        let config = BetfairDataClientConfig {
653            event_type_names: Some(vec!["Horse Racing".to_string()]),
654            market_ids: Some(vec!["1.234567".to_string()]),
655            ..Default::default()
656        };
657
658        let filter = config.navigation_filter();
659
660        assert_eq!(
661            filter.event_type_names,
662            Some(vec!["Horse Racing".to_string()])
663        );
664        assert_eq!(filter.market_ids, Some(vec!["1.234567".to_string()]));
665    }
666
667    #[rstest]
668    fn test_data_config_stream_config() {
669        let config = BetfairDataClientConfig {
670            stream_host: Some("localhost".to_string()),
671            stream_port: Some(9443),
672            stream_heartbeat_secs: Some(3),
673            stream_heartbeat_timeout_secs: Some(30),
674            stream_reconnect_delay_initial_ms: 500,
675            stream_reconnect_delay_max_ms: 5_000,
676            stream_use_tls: false,
677            ..Default::default()
678        };
679
680        let stream_config = config.stream_config();
681
682        assert_eq!(stream_config.host, "localhost");
683        assert_eq!(stream_config.port, 9443);
684        assert_eq!(stream_config.heartbeat_secs, Some(3));
685        assert_eq!(stream_config.heartbeat_timeout_secs, Some(30));
686        assert_eq!(stream_config.reconnect_delay_initial_ms, 500);
687        assert_eq!(stream_config.reconnect_delay_max_ms, 5_000);
688        assert!(!stream_config.use_tls);
689    }
690
691    #[rstest]
692    fn test_data_config_stream_config_uses_defaults() {
693        let config = BetfairDataClientConfig::default();
694
695        let stream_config = config.stream_config();
696
697        assert_eq!(stream_config.host, BetfairStreamConfig::default().host);
698        assert_eq!(stream_config.port, BetfairStreamConfig::default().port);
699    }
700
701    #[rstest]
702    fn test_data_config_credential_rejects_partial_credentials() {
703        let config = BetfairDataClientConfig {
704            username: Some("testuser".into()),
705            ..Default::default()
706        };
707
708        let result = config.credential();
709
710        assert!(result.is_err());
711        assert!(
712            result
713                .err()
714                .unwrap()
715                .to_string()
716                .contains("password is missing")
717        );
718    }
719
720    #[rstest]
721    fn test_exec_config_default() {
722        let config = BetfairExecutionClientConfig::default();
723        assert_eq!(config.account_id, AccountId::from("BETFAIR-001"));
724        assert_eq!(config.account_currency, "GBP");
725        assert_eq!(config.request_rate_per_second, 5);
726        assert_eq!(config.order_request_rate_per_second, 20);
727        assert_eq!(config.stream_heartbeat_secs, None);
728        assert_eq!(config.stream_heartbeat_timeout_secs, None);
729        assert!(config.stream_market_ids_filter.is_none());
730        assert!(!config.ignore_external_orders);
731        assert!(config.calculate_account_state);
732        assert_eq!(config.request_account_state_secs, 300);
733        assert!(!config.reconcile_market_ids_only);
734        assert!(config.reconcile_market_ids.is_none());
735        assert!(!config.use_market_version);
736    }
737
738    #[rstest]
739    fn test_exec_config_with_market_filter() {
740        let config = BetfairExecutionClientConfig {
741            stream_market_ids_filter: Some(vec!["1.234567".to_string(), "1.890123".to_string()]),
742            ..Default::default()
743        };
744
745        let filter = config.stream_market_ids_filter.as_ref().unwrap();
746        assert_eq!(filter.len(), 2);
747        assert!(filter.contains(&"1.234567".to_string()));
748    }
749
750    #[rstest]
751    fn test_exec_config_external_orders_ignored() {
752        let config = BetfairExecutionClientConfig {
753            ignore_external_orders: true,
754            ..Default::default()
755        };
756
757        assert!(config.ignore_external_orders);
758    }
759
760    #[rstest]
761    fn test_exec_config_account_state_disabled() {
762        let config = BetfairExecutionClientConfig {
763            calculate_account_state: false,
764            ..Default::default()
765        };
766
767        assert!(!config.calculate_account_state);
768    }
769
770    #[rstest]
771    fn test_exec_config_reconcile_market_ids() {
772        let config = BetfairExecutionClientConfig {
773            reconcile_market_ids_only: true,
774            reconcile_market_ids: Some(vec!["1.234567".to_string()]),
775            ..Default::default()
776        };
777
778        assert!(config.reconcile_market_ids_only);
779        assert_eq!(config.reconcile_market_ids.as_ref().unwrap().len(), 1);
780    }
781
782    #[rstest]
783    fn test_exec_config_use_market_version() {
784        let config = BetfairExecutionClientConfig {
785            use_market_version: true,
786            ..Default::default()
787        };
788
789        assert!(config.use_market_version);
790    }
791
792    #[rstest]
793    fn test_exec_config_validate_rejects_zero_order_rate_limit() {
794        let config = BetfairExecutionClientConfig {
795            order_request_rate_per_second: 0,
796            ..Default::default()
797        };
798
799        let result = config.validate();
800        assert!(result.is_err());
801        assert!(
802            result
803                .err()
804                .unwrap()
805                .to_string()
806                .contains("order_request_rate_per_second")
807        );
808    }
809
810    #[rstest]
811    fn test_exec_config_validate_rejects_invalid_currency() {
812        let config = BetfairExecutionClientConfig {
813            account_currency: "INVALID".to_string(),
814            ..Default::default()
815        };
816
817        let result = config.validate();
818
819        assert!(result.is_err());
820        assert!(
821            result
822                .err()
823                .unwrap()
824                .to_string()
825                .contains("Invalid account currency")
826        );
827    }
828
829    #[rstest]
830    fn test_data_config_validate_rejects_bad_market_start_time() {
831        let config = BetfairDataClientConfig {
832            min_market_start_time: Some("not-a-timestamp".to_string()),
833            ..Default::default()
834        };
835
836        let result = config.validate();
837        assert!(result.is_err());
838        assert!(
839            result
840                .err()
841                .unwrap()
842                .to_string()
843                .contains("min_market_start_time")
844        );
845    }
846
847    #[rstest]
848    fn test_data_config_min_notional() {
849        let config = BetfairDataClientConfig {
850            default_min_notional: Some(Decimal::new(2, 0)),
851            ..Default::default()
852        };
853
854        let min_notional = config.min_notional().unwrap();
855        assert_eq!(
856            min_notional,
857            Some(Money::from_decimal(Decimal::new(2, 0), Currency::GBP()).unwrap())
858        );
859    }
860
861    #[rstest]
862    fn test_data_config_toml_minimal() {
863        let config: BetfairDataClientConfig = toml::from_str(
864            r#"
865account_currency = "USD"
866request_rate_per_second = 10
867stream_heartbeat_secs = 3
868stream_heartbeat_timeout_secs = 30
869stream_reconnect_delay_initial_ms = 500
870stream_reconnect_delay_max_ms = 5000
871stream_use_tls = false
872subscription_delay_secs = 1
873subscribe_race_data = true
874subscribe_cricket_data = true
875"#,
876        )
877        .unwrap();
878
879        assert_eq!(config.account_currency, "USD");
880        assert_eq!(config.request_rate_per_second, 10);
881        assert_eq!(config.stream_heartbeat_secs, Some(3));
882        assert!(!config.stream_use_tls);
883        assert!(config.subscribe_race_data);
884        assert!(config.subscribe_cricket_data);
885    }
886
887    #[rstest]
888    fn test_exec_config_toml_empty_uses_defaults() {
889        let config: BetfairExecutionClientConfig = toml::from_str("").unwrap();
890        let expected = BetfairExecutionClientConfig::default();
891        assert_eq!(config.account_id, expected.account_id);
892        assert_eq!(config.account_currency, expected.account_currency);
893        assert_eq!(
894            config.request_rate_per_second,
895            expected.request_rate_per_second,
896        );
897        assert_eq!(
898            config.order_request_rate_per_second,
899            expected.order_request_rate_per_second,
900        );
901        assert_eq!(config.stream_heartbeat_secs, expected.stream_heartbeat_secs);
902        assert_eq!(config.stream_use_tls, expected.stream_use_tls);
903        assert_eq!(
904            config.calculate_account_state,
905            expected.calculate_account_state,
906        );
907    }
908}