nautilus_finfeed/
factories.rs1use std::{any::Any, cell::RefCell, rc::Rc};
19
20use nautilus_common::{
21 cache::CacheView,
22 clients::DataClient,
23 clock::Clock,
24 factories::{ClientConfig, DataClientFactory},
25 live::runner::try_get_data_event_sender,
26};
27use nautilus_model::identifiers::ClientId;
28
29use crate::{common::consts::FINFEED, config::FinFeedDataClientConfig, data::FinFeedDataClient};
30
31#[derive(Debug, Clone)]
33#[cfg_attr(
34 feature = "python",
35 pyo3::pyclass(module = "nautilus_trader.adapters.finfeed", from_py_object)
36)]
37#[cfg_attr(
38 feature = "python",
39 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
40)]
41pub struct FinFeedDataClientFactory;
42
43impl FinFeedDataClientFactory {
44 #[must_use]
46 pub const fn new() -> Self {
47 Self
48 }
49}
50
51impl Default for FinFeedDataClientFactory {
52 fn default() -> Self {
53 Self::new()
54 }
55}
56
57impl DataClientFactory for FinFeedDataClientFactory {
58 fn create(
59 &self,
60 name: &str,
61 config: &dyn ClientConfig,
62 _cache: CacheView,
63 _clock: Rc<RefCell<dyn Clock>>,
64 ) -> anyhow::Result<Box<dyn DataClient>> {
65 let finfeed_config = config
66 .as_any()
67 .downcast_ref::<FinFeedDataClientConfig>()
68 .ok_or_else(|| {
69 anyhow::anyhow!(
70 "Invalid config type for FinFeedDataClientFactory. Expected FinFeedDataClientConfig, was {config:?}",
71 )
72 })?
73 .clone();
74
75 let client_id = ClientId::from(name);
76 let sender = try_get_data_event_sender()
77 .ok_or_else(|| anyhow::anyhow!("FinFeed data event sender is not initialized"))?;
78 let client = FinFeedDataClient::new(client_id, finfeed_config, sender)?;
79 Ok(Box::new(client))
80 }
81
82 fn name(&self) -> &'static str {
84 FINFEED
85 }
86
87 fn config_type(&self) -> &'static str {
88 "FinFeedDataClientConfig"
89 }
90}
91
92impl ClientConfig for FinFeedDataClientConfig {
93 fn as_any(&self) -> &dyn Any {
94 self
95 }
96}
97
98#[cfg(test)]
99mod tests {
100 use nautilus_common::{
101 cache::Cache, clock::VirtualClock, live::runner::replace_data_event_sender,
102 };
103 use nautilus_core::string::secret::SecretString;
104 use rstest::rstest;
105
106 use super::*;
107 use crate::instruments::FinFeedInstrumentSelection;
108
109 fn create(config: &dyn ClientConfig) -> anyhow::Result<Box<dyn DataClient>> {
110 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
111 replace_data_event_sender(sender);
112 let cache = Rc::new(RefCell::new(Cache::default()));
113 let clock = Rc::new(RefCell::new(VirtualClock::new()));
114 FinFeedDataClientFactory::new().create("FINFEED-TEST", config, cache.into(), clock)
115 }
116
117 fn config() -> FinFeedDataClientConfig {
118 FinFeedDataClientConfig::builder()
119 .api_key(SecretString::from("factory-test-key"))
120 .instruments(vec![FinFeedInstrumentSelection {
121 exchange_id: "POLYMARKET".into(),
122 market_ids: vec!["market_YES".into()],
123 }])
124 .build()
125 }
126
127 #[rstest]
128 fn creates_named_multivenue_client() {
129 let factory = FinFeedDataClientFactory::new();
130 let config = config();
131 let client = create(&config).unwrap();
132 assert_eq!(factory.name(), "FINFEED");
133 assert_eq!(factory.config_type(), "FinFeedDataClientConfig");
134 assert_eq!(client.client_id(), ClientId::from("FINFEED-TEST"));
135 assert_eq!(client.venue(), None);
136 assert!(client.is_disconnected());
137 }
138
139 #[rstest]
140 fn config_downcasts_from_client_config() {
141 let config: Box<dyn ClientConfig> = Box::new(config());
142 assert_eq!(
143 config
144 .as_any()
145 .downcast_ref::<FinFeedDataClientConfig>()
146 .unwrap()
147 .instruments[0]
148 .market_ids,
149 ["market_YES"]
150 );
151 }
152
153 #[rstest]
154 #[case("selection", "instrument selection is empty")]
155 #[case("poll_interval", "poll_interval_ms must be in [100, 86400000], was 99")]
156 #[case("poll_limit", "poll_limit must be in [1, 10000], was 0")]
157 #[case("connect_timeout", "connect_timeout_secs must be in [1, 86400], was 0")]
158 #[case(
159 "http_timeout",
160 "within one day: http_timeout_secs (http.timeout_secs)"
161 )]
162 #[case("attempt_budget", "within one day: attempt_budget")]
163 #[case("concurrency", "within one day: max_concurrent_requests")]
164 #[case("request_interval", "within one day: min_request_interval_ms")]
165 #[case(
166 "retry_timeout",
167 "within one day: retry_operation_timeout_ms (http.retry.operation_timeout_ms)"
168 )]
169 #[case(
170 "retry_elapsed",
171 "within one day: retry_max_elapsed_ms (http.retry.max_elapsed_ms)"
172 )]
173 #[case("retry_backoff", "invalid retry backoff")]
174 #[case("base_url", "base URL must be HTTPS")]
175 #[case("proxy", "invalid proxy URL")]
176 fn propagates_client_validation(#[case] field: &str, #[case] expected: &str) {
177 let mut config = config();
178 match field {
179 "selection" => config.instruments.clear(),
180 "poll_interval" => config.poll_interval_ms = 99,
181 "poll_limit" => config.poll_limit = 0,
182 "connect_timeout" => config.connect_timeout_secs = 0,
183 "http_timeout" => config.http.timeout_secs = 0,
184 "attempt_budget" => config.http.attempt_budget = 0,
185 "concurrency" => config.http.max_concurrent_requests = 0,
186 "request_interval" => config.http.min_request_interval_ms = 0,
187 "retry_timeout" => config.http.retry.operation_timeout_ms = None,
188 "retry_elapsed" => config.http.retry.max_elapsed_ms = None,
189 "retry_backoff" => config.http.retry.backoff_factor = 0.0,
190 "base_url" => config.http.base_url = "http://example.com/".into(),
191 "proxy" => config.http.proxy_url = Some(SecretString::from("bad proxy")),
192 _ => unreachable!(),
193 }
194
195 let error = create(&config).err().unwrap().to_string();
196 assert!(error.contains(expected), "{error}");
197 }
198
199 #[rstest]
200 fn missing_runner_sender_returns_error() {
201 let error = std::thread::spawn(|| {
202 let cache = Rc::new(RefCell::new(Cache::default()));
203 let clock = Rc::new(RefCell::new(VirtualClock::new()));
204 FinFeedDataClientFactory::new()
205 .create("FINFEED-TEST", &config(), cache.into(), clock)
206 .err()
207 .unwrap()
208 .to_string()
209 })
210 .join()
211 .unwrap();
212
213 assert_eq!(error, "FinFeed data event sender is not initialized");
214 }
215
216 #[rstest]
217 fn rejects_wrong_config_type() {
218 #[derive(Debug)]
219 struct WrongConfig;
220 impl ClientConfig for WrongConfig {
221 fn as_any(&self) -> &dyn Any {
222 self
223 }
224 }
225 let error = create(&WrongConfig).err().unwrap().to_string();
226 assert_eq!(
227 error,
228 "Invalid config type for FinFeedDataClientFactory. Expected FinFeedDataClientConfig, was WrongConfig"
229 );
230 }
231}