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