Skip to main content

nautilus_coinbase/
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 Coinbase adapter.
17
18#[cfg(test)]
19use nautilus_core::string::secret::REDACTED;
20use nautilus_core::string::secret::SecretString;
21use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
22use nautilus_model::{enums::AccountType, identifiers::AccountId};
23use nautilus_network::websocket::TransportBackend;
24use serde::{Deserialize, Serialize};
25
26use crate::common::{
27    enums::{CoinbaseEnvironment, CoinbaseMarginType},
28    urls,
29};
30
31/// Configuration for the Coinbase data client.
32#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
33#[serde(default, deny_unknown_fields)]
34#[cfg_attr(
35    feature = "python",
36    pyo3::pyclass(module = "nautilus_trader.adapters.coinbase", from_py_object)
37)]
38#[cfg_attr(
39    feature = "python",
40    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.coinbase")
41)]
42pub struct CoinbaseDataClientConfig {
43    /// CDP API key name (falls back to `COINBASE_API_KEY` env var).
44    pub api_key: Option<SecretString>,
45    /// CDP API secret in PEM format (falls back to `COINBASE_API_SECRET` env var).
46    pub api_secret: Option<SecretString>,
47    /// The Coinbase environment to connect to.
48    #[builder(default)]
49    pub environment: CoinbaseEnvironment,
50    /// Override for the REST API base URL.
51    pub base_url_rest: Option<String>,
52    /// Override for the WebSocket market data URL.
53    pub base_url_ws: Option<String>,
54    /// Optional proxy URL for HTTP and WebSocket transports.
55    pub proxy_url: Option<SecretString>,
56    /// HTTP timeout in seconds.
57    #[builder(default = 10)]
58    pub http_timeout_secs: u64,
59    /// WebSocket timeout in seconds.
60    #[builder(default = 30)]
61    pub ws_timeout_secs: u64,
62    /// Interval for refreshing instruments in minutes.
63    #[builder(default = 60)]
64    pub update_instruments_interval_mins: u64,
65    /// Seconds between REST polls for derivatives-only data streams
66    /// (`IndexPriceUpdate`, `FundingRateUpdate`). Coinbase Advanced Trade
67    /// does not publish these on a WebSocket channel, so they are sourced
68    /// from periodic `/products/{id}` fetches.
69    #[builder(default = 15)]
70    pub derivatives_poll_interval_secs: u64,
71    /// Maximum time to wait for an initial, post-reconnect, or recovery order book
72    /// snapshot in seconds. Set to 0 to disable snapshot deadlines.
73    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
74    pub book_snapshot_timeout_secs: u64,
75    /// WebSocket transport backend (defaults to `Tungstenite`).
76    #[builder(default)]
77    pub transport_backend: TransportBackend,
78}
79
80#[cfg(feature = "python")]
81nautilus_core::impl_pyo3_config_getters!(CoinbaseDataClientConfig {
82    environment: CoinbaseEnvironment,
83    base_url_rest: Option<String>,
84    base_url_ws: Option<String>,
85    http_timeout_secs: u64,
86    ws_timeout_secs: u64,
87    update_instruments_interval_mins: u64,
88    derivatives_poll_interval_secs: u64,
89    book_snapshot_timeout_secs: u64,
90    transport_backend: TransportBackend,
91});
92
93impl Default for CoinbaseDataClientConfig {
94    fn default() -> Self {
95        Self::builder().build()
96    }
97}
98
99impl CoinbaseDataClientConfig {
100    /// Creates a new configuration with default settings.
101    #[must_use]
102    pub fn new() -> Self {
103        Self::default()
104    }
105
106    /// Returns true when credentials are populated and non-empty.
107    #[must_use]
108    pub fn has_credentials(&self) -> bool {
109        self.api_key
110            .as_ref()
111            .map(SecretString::expose_secret)
112            .is_some_and(|s| !s.trim().is_empty())
113            && self
114                .api_secret
115                .as_ref()
116                .map(SecretString::expose_secret)
117                .is_some_and(|s| !s.trim().is_empty())
118    }
119
120    /// Returns the REST API base URL, respecting environment and overrides.
121    #[must_use]
122    pub fn rest_url(&self) -> String {
123        self.base_url_rest
124            .clone()
125            .unwrap_or_else(|| urls::rest_url(self.environment).to_string())
126    }
127
128    /// Returns the WebSocket market data URL, respecting environment and overrides.
129    #[must_use]
130    pub fn ws_url(&self) -> String {
131        self.base_url_ws
132            .clone()
133            .unwrap_or_else(|| urls::ws_url(self.environment).to_string())
134    }
135}
136
137/// Configuration for the Coinbase execution client.
138#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
139#[serde(default, deny_unknown_fields)]
140#[cfg_attr(
141    feature = "python",
142    pyo3::pyclass(module = "nautilus_trader.adapters.coinbase", from_py_object)
143)]
144#[cfg_attr(
145    feature = "python",
146    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.coinbase")
147)]
148pub struct CoinbaseExecutionClientConfig {
149    /// Account identifier for the execution client.
150    #[builder(default = AccountId::from("COINBASE-001"))]
151    pub account_id: AccountId,
152    /// CDP API key name (falls back to `COINBASE_API_KEY` env var).
153    pub api_key: Option<SecretString>,
154    /// CDP API secret in PEM format (falls back to `COINBASE_API_SECRET` env var).
155    pub api_secret: Option<SecretString>,
156    /// Environment to connect to.
157    #[builder(default)]
158    pub environment: CoinbaseEnvironment,
159    /// Optional override for the REST API base URL.
160    pub base_url_rest: Option<String>,
161    /// Optional override for the WebSocket user data URL.
162    pub base_url_ws: Option<String>,
163    /// Optional proxy URL for HTTP and WebSocket transports.
164    pub proxy_url: Option<SecretString>,
165    /// Timeout in seconds for HTTP requests.
166    #[builder(default = 10)]
167    pub http_timeout_secs: u64,
168    /// Maximum number of retry attempts for HTTP requests.
169    #[builder(default = 3)]
170    pub max_retries: u32,
171    /// Initial retry delay in milliseconds.
172    #[builder(default = 100)]
173    pub retry_delay_initial_ms: u64,
174    /// Maximum HTTP retry delay and recovery polling interval, in milliseconds.
175    /// Recovery polls use at least 1 ms and continue while connected.
176    #[builder(default = 5000)]
177    pub retry_delay_max_ms: u64,
178    /// Selects the execution scope: `Cash` for spot, `Margin` for CFM
179    /// derivatives. `CoinbaseExecutionClientFactory` rejects other values.
180    #[builder(default = AccountType::Cash)]
181    pub account_type: AccountType,
182    /// Optional default margin type applied to derivatives orders. Ignored on
183    /// Cash accounts.
184    pub default_margin_type: Option<CoinbaseMarginType>,
185    /// Optional default leverage applied to derivatives orders. Ignored on
186    /// Cash accounts.
187    pub default_leverage: Option<rust_decimal::Decimal>,
188    /// CDP retail portfolio UUID required when the API key is bound to a
189    /// non-default portfolio. When unset, the venue uses the key's default
190    /// portfolio. Coinbase rejects orders with `"account is not available"`
191    /// if the portfolio is non-default and this field is omitted.
192    pub retail_portfolio_id: Option<String>,
193    /// WebSocket transport backend (defaults to `Tungstenite`).
194    #[builder(default)]
195    pub transport_backend: TransportBackend,
196}
197
198#[cfg(feature = "python")]
199nautilus_core::impl_pyo3_config_getters!(CoinbaseExecutionClientConfig {
200    account_id: AccountId,
201    environment: CoinbaseEnvironment,
202    base_url_rest: Option<String>,
203    base_url_ws: Option<String>,
204    http_timeout_secs: u64,
205    max_retries: u32,
206    retry_delay_initial_ms: u64,
207    retry_delay_max_ms: u64,
208    account_type: AccountType,
209    default_margin_type: Option<CoinbaseMarginType>,
210    default_leverage: Option<rust_decimal::Decimal>,
211    retail_portfolio_id: Option<String>,
212    transport_backend: TransportBackend,
213});
214
215impl Default for CoinbaseExecutionClientConfig {
216    fn default() -> Self {
217        Self::builder().build()
218    }
219}
220
221impl CoinbaseExecutionClientConfig {
222    /// Creates a new configuration with default settings.
223    #[must_use]
224    pub fn new() -> Self {
225        Self::default()
226    }
227
228    /// Returns true when credentials are populated and non-empty.
229    #[must_use]
230    pub fn has_credentials(&self) -> bool {
231        self.api_key
232            .as_ref()
233            .map(SecretString::expose_secret)
234            .is_some_and(|s| !s.trim().is_empty())
235            && self
236                .api_secret
237                .as_ref()
238                .map(SecretString::expose_secret)
239                .is_some_and(|s| !s.trim().is_empty())
240    }
241
242    /// Returns the REST API base URL, respecting environment and overrides.
243    #[must_use]
244    pub fn rest_url(&self) -> String {
245        self.base_url_rest
246            .clone()
247            .unwrap_or_else(|| urls::rest_url(self.environment).to_string())
248    }
249
250    /// Returns the WebSocket user data URL, respecting environment and overrides.
251    #[must_use]
252    pub fn ws_url(&self) -> String {
253        self.base_url_ws
254            .clone()
255            .unwrap_or_else(|| urls::ws_user_url(self.environment).to_string())
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use rstest::rstest;
262
263    use super::*;
264
265    #[rstest]
266    fn test_config_debug_redacts_credentials() {
267        let data = CoinbaseDataClientConfig {
268            api_key: Some("data-api-key".into()),
269            api_secret: Some("data-api-secret".into()),
270            proxy_url: Some("http://user:data-proxy@localhost".into()),
271            ..Default::default()
272        };
273        let execution = CoinbaseExecutionClientConfig {
274            api_key: Some("exec-api-key".into()),
275            api_secret: Some("exec-api-secret".into()),
276            proxy_url: Some("http://user:exec-proxy@localhost".into()),
277            ..Default::default()
278        };
279
280        let formatted = format!("{data:?} {execution:?}");
281
282        assert_eq!(formatted.matches(REDACTED).count(), 6);
283
284        for secret in [
285            "data-api-key",
286            "data-api-secret",
287            "data-proxy",
288            "exec-api-key",
289            "exec-api-secret",
290            "exec-proxy",
291        ] {
292            assert!(!formatted.contains(secret));
293        }
294    }
295
296    #[rstest]
297    fn test_data_config_defaults() {
298        let config = CoinbaseDataClientConfig::default();
299        assert_eq!(config.environment, CoinbaseEnvironment::Live);
300        assert_eq!(config.http_timeout_secs, 10);
301        assert_eq!(config.ws_timeout_secs, 30);
302        assert_eq!(config.update_instruments_interval_mins, 60);
303        assert_eq!(config.book_snapshot_timeout_secs, 10);
304        assert!(!config.has_credentials());
305    }
306
307    #[rstest]
308    fn test_data_config_has_credentials() {
309        let config = CoinbaseDataClientConfig {
310            api_key: Some("key".into()),
311            api_secret: Some("secret".into()),
312            ..CoinbaseDataClientConfig::default()
313        };
314        assert!(config.has_credentials());
315    }
316
317    #[rstest]
318    fn test_data_config_empty_credentials() {
319        let config = CoinbaseDataClientConfig {
320            api_key: Some("  ".into()),
321            api_secret: Some("secret".into()),
322            ..CoinbaseDataClientConfig::default()
323        };
324        assert!(!config.has_credentials());
325    }
326
327    #[rstest]
328    fn test_data_config_urls_live() {
329        let config = CoinbaseDataClientConfig::default();
330        assert!(config.rest_url().contains("api.coinbase.com"));
331        assert!(config.ws_url().contains("advanced-trade-ws.coinbase.com"));
332    }
333
334    #[rstest]
335    fn test_data_config_urls_sandbox() {
336        let config = CoinbaseDataClientConfig {
337            environment: CoinbaseEnvironment::Sandbox,
338            ..CoinbaseDataClientConfig::default()
339        };
340        assert!(config.rest_url().contains("sandbox"));
341        assert!(config.ws_url().contains("sandbox"));
342    }
343
344    #[rstest]
345    fn test_exec_config_defaults() {
346        let config = CoinbaseExecutionClientConfig::default();
347        assert_eq!(config.environment, CoinbaseEnvironment::Live);
348        assert_eq!(config.http_timeout_secs, 10);
349        assert_eq!(config.max_retries, 3);
350    }
351
352    #[rstest]
353    fn test_exec_config_ws_url_uses_user_endpoint() {
354        let config = CoinbaseExecutionClientConfig::default();
355        assert!(config.ws_url().contains("user"));
356    }
357
358    #[rstest]
359    fn test_data_config_toml_minimal() {
360        let config: CoinbaseDataClientConfig = toml::from_str(
361            r#"
362environment = "Sandbox"
363http_timeout_secs = 5
364update_instruments_interval_mins = 30
365derivatives_poll_interval_secs = 60
366"#,
367        )
368        .unwrap();
369
370        assert_eq!(config.environment, CoinbaseEnvironment::Sandbox);
371        assert_eq!(config.http_timeout_secs, 5);
372        assert_eq!(config.update_instruments_interval_mins, 30);
373        assert_eq!(config.derivatives_poll_interval_secs, 60);
374    }
375
376    #[rstest]
377    fn test_exec_config_toml_empty_uses_defaults() {
378        let config: CoinbaseExecutionClientConfig = toml::from_str("").unwrap();
379        let expected = CoinbaseExecutionClientConfig::default();
380
381        assert_eq!(config.environment, expected.environment);
382        assert_eq!(config.http_timeout_secs, expected.http_timeout_secs);
383        assert_eq!(config.max_retries, expected.max_retries);
384        assert_eq!(config.account_type, expected.account_type);
385        assert_eq!(config.transport_backend, expected.transport_backend);
386    }
387}