Skip to main content

nautilus_hyperliquid/
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 Hyperliquid 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::identifiers::AccountId;
23use nautilus_network::websocket::TransportBackend;
24use serde::{Deserialize, Serialize};
25use strum::IntoEnumIterator;
26
27use crate::common::{
28    consts::{info_url, ws_url},
29    enums::{HyperliquidEnvironment, HyperliquidProductType},
30};
31
32/// Venue source for the shared Hyperliquid order book.
33#[derive(
34    Debug,
35    Clone,
36    Copy,
37    Default,
38    PartialEq,
39    Eq,
40    Serialize,
41    Deserialize,
42    strum::AsRefStr,
43    strum::EnumString,
44)]
45pub enum HyperliquidBookFeed {
46    /// Documented full-snapshot feed.
47    #[default]
48    #[serde(rename = "l2Book")]
49    #[strum(serialize = "l2Book")]
50    L2Book,
51    /// Compact snapshot/update feed used by the web application.
52    #[serde(rename = "l2")]
53    #[strum(serialize = "l2")]
54    L2,
55}
56
57/// Configuration for the Hyperliquid data client.
58///
59/// The `stale_stream_*` options control the stream health monitor. With recovery
60/// enabled, a stale stream is warned about first, then acted on once per recovery
61/// cooldown. A stale order book delta stream, including depth that shares its stream,
62/// starts shared book recovery, which resubscribes until a fresh snapshot arrives.
63/// Depth-only and BBO streams receive a targeted resubscribe (preserving the original
64/// `l2Book` options) and escalate to a full WebSocket reconnect after
65/// `stale_stream_max_targeted_resubscribes` failed attempts. Fresh data resets the ladder. See the Hyperliquid integration guide
66/// ("Stream health and recovery") for details.
67#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
68#[serde(default, deny_unknown_fields)]
69#[cfg_attr(
70    feature = "python",
71    pyo3::pyclass(module = "nautilus_trader.adapters.hyperliquid", from_py_object)
72)]
73#[cfg_attr(
74    feature = "python",
75    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.hyperliquid")
76)]
77pub struct HyperliquidDataClientConfig {
78    /// Optional private key for authenticated endpoints.
79    pub private_key: Option<SecretString>,
80    /// The target environment (mainnet or testnet).
81    #[builder(default)]
82    pub environment: HyperliquidEnvironment,
83    /// Override for the HTTP info URL.
84    pub base_url_http: Option<String>,
85    /// Override for the WebSocket URL.
86    pub base_url_ws: Option<String>,
87    /// Order book source, fixed for the client lifetime (`l2Book` by default).
88    #[builder(default)]
89    pub book_feed: HyperliquidBookFeed,
90    /// Optional proxy URL for HTTP and WebSocket transports.
91    pub proxy_url: Option<SecretString>,
92    /// HTTP timeout in seconds.
93    ///
94    /// Also bounds each complete instrument request, including time queued behind another refresh.
95    #[builder(default = 60)]
96    pub http_timeout_secs: u64,
97    /// WebSocket timeout in seconds.
98    #[builder(default = 30)]
99    pub ws_timeout_secs: u64,
100    /// Receive-age threshold in seconds for warning about stale market-data streams.
101    /// Choose a value above the instrument's expected quiet period.
102    /// Set to 0 to disable the stream health monitor.
103    #[builder(default = 120)]
104    pub stale_stream_receive_timeout_secs: u64,
105    /// Interval in seconds for running market-data stream health checks.
106    /// Set to 0 to disable the stream health monitor.
107    #[builder(default = 15)]
108    pub stream_health_check_interval_secs: u64,
109    /// Cooldown in seconds between stale warnings for the same market-data stream.
110    #[builder(default = 60)]
111    pub stale_stream_warning_cooldown_secs: u64,
112    /// Enables automated stale-stream recovery. Off by default: the stream health
113    /// monitor warns only and never changes subscriptions.
114    #[builder(default = false)]
115    pub stale_stream_recovery_enabled: bool,
116    /// Cooldown in seconds between recovery actions for the same market-data stream.
117    /// Must be positive for recovery to run.
118    #[builder(default = 120)]
119    pub stale_stream_recovery_cooldown_secs: u64,
120    /// Targeted resubscribe attempts for a stale depth-only or BBO stream before
121    /// escalating to a full WebSocket reconnect.
122    #[builder(default = 3)]
123    pub stale_stream_max_targeted_resubscribes: u32,
124    /// Maximum time to wait for an initial, post-reconnect, or recovery order book
125    /// snapshot in seconds.
126    ///
127    /// Set to 0 to disable snapshot deadlines.
128    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
129    pub book_snapshot_timeout_secs: u64,
130    /// Interval for refreshing instruments in minutes.
131    ///
132    /// Set to 0 to disable the periodic refresh.
133    #[builder(default = 60)]
134    pub update_instruments_interval_mins: u64,
135    /// WebSocket transport backend (`Sockudo` by default; `Tungstenite` when
136    /// the `transport-sockudo` feature is disabled).
137    #[builder(default)]
138    pub transport_backend: TransportBackend,
139}
140
141#[cfg(feature = "python")]
142nautilus_core::impl_pyo3_config_getters!(HyperliquidDataClientConfig {
143    environment: HyperliquidEnvironment,
144    base_url_http: Option<String>,
145    base_url_ws: Option<String>,
146    http_timeout_secs: u64,
147    ws_timeout_secs: u64,
148    update_instruments_interval_mins: u64,
149    transport_backend: TransportBackend,
150    stale_stream_receive_timeout_secs: u64,
151    stream_health_check_interval_secs: u64,
152    stale_stream_warning_cooldown_secs: u64,
153    stale_stream_recovery_enabled: bool,
154    stale_stream_recovery_cooldown_secs: u64,
155    stale_stream_max_targeted_resubscribes: u32,
156    book_snapshot_timeout_secs: u64,
157});
158
159impl Default for HyperliquidDataClientConfig {
160    fn default() -> Self {
161        Self::builder().build()
162    }
163}
164
165impl HyperliquidDataClientConfig {
166    /// Creates a new configuration with default settings.
167    #[must_use]
168    pub fn new() -> Self {
169        Self::default()
170    }
171
172    /// Returns `true` when private key is populated and non-empty.
173    #[must_use]
174    pub fn has_credentials(&self) -> bool {
175        self.private_key
176            .as_ref()
177            .map(SecretString::expose_secret)
178            .is_some_and(|s| !s.trim().is_empty())
179    }
180
181    /// Returns the WebSocket URL, respecting the environment and overrides.
182    #[must_use]
183    pub fn ws_url(&self) -> String {
184        self.base_url_ws
185            .clone()
186            .unwrap_or_else(|| ws_url(self.environment).to_string())
187    }
188
189    /// Returns the HTTP info URL, respecting the environment and overrides.
190    #[must_use]
191    pub fn http_url(&self) -> String {
192        self.base_url_http
193            .clone()
194            .unwrap_or_else(|| info_url(self.environment).to_string())
195    }
196}
197
198/// Configuration for the Hyperliquid execution client.
199#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
200#[serde(default, deny_unknown_fields)]
201#[cfg_attr(
202    feature = "python",
203    pyo3::pyclass(module = "nautilus_trader.adapters.hyperliquid", from_py_object)
204)]
205#[cfg_attr(
206    feature = "python",
207    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.hyperliquid")
208)]
209pub struct HyperliquidExecutionClientConfig {
210    /// Products covered by order commands, private reports, and reconciliation.
211    /// Defaults to all products. Account balances remain account-wide.
212    #[builder(default = HyperliquidProductType::iter().collect())]
213    pub product_types: Vec<HyperliquidProductType>,
214    /// Account identifier for the execution client.
215    #[builder(default = AccountId::from("HYPERLIQUID-001"))]
216    pub account_id: AccountId,
217    /// Private key for signing transactions.
218    ///
219    /// If not provided, falls back to environment variable:
220    /// - Mainnet: `HYPERLIQUID_PK`
221    /// - Testnet: `HYPERLIQUID_TESTNET_PK`
222    pub private_key: Option<SecretString>,
223    /// Optional vault address for vault operations.
224    ///
225    /// If not provided, falls back to environment variable:
226    /// - Mainnet: `HYPERLIQUID_VAULT`
227    /// - Testnet: `HYPERLIQUID_TESTNET_VAULT`
228    pub vault_address: Option<String>,
229    /// Optional main account address when using an agent wallet (API sub-key).
230    /// When set, used for balance queries, position reports, and WS subscriptions
231    /// instead of the address derived from the private key.
232    ///
233    /// If not provided and no explicit vault address is set, falls back to
234    /// the `HYPERLIQUID_ACCOUNT_ADDRESS` environment variable.
235    pub account_address: Option<String>,
236    /// The target environment (mainnet or testnet).
237    #[builder(default)]
238    pub environment: HyperliquidEnvironment,
239    /// Override for the HTTP info URL.
240    pub base_url_http: Option<String>,
241    /// Override for the WebSocket URL.
242    pub base_url_ws: Option<String>,
243    /// Override for the exchange API URL.
244    pub base_url_exchange: Option<String>,
245    /// Optional proxy URL for HTTP and WebSocket transports.
246    pub proxy_url: Option<SecretString>,
247    /// HTTP timeout in seconds.
248    #[builder(default = 60)]
249    pub http_timeout_secs: u64,
250    /// Maximum retries after the initial attempt for read-only HTTP info requests.
251    /// Zero disables retries. Does not apply to exchange actions or WebSocket posts.
252    #[builder(default = 3)]
253    pub max_retries: u32,
254    /// Initial full-jitter backoff bound for HTTP info retries, in milliseconds.
255    /// Zero disables backoff. A valid `Retry-After` header overrides backoff.
256    #[builder(default = 100)]
257    pub retry_delay_initial_ms: u64,
258    /// Maximum full-jitter backoff bound for HTTP info retries, in milliseconds.
259    /// Zero disables backoff. Does not cap a valid `Retry-After` header.
260    #[builder(default = 5000)]
261    pub retry_delay_max_ms: u64,
262    /// When true, normalize order prices to 5 significant figures
263    /// before submission (Hyperliquid requirement).
264    #[builder(default = true)]
265    pub normalize_prices: bool,
266    /// Slippage buffer in basis points applied to MARKET orders and
267    /// stop-to-limit trigger derivations. Can be overridden per-order via
268    /// `SubmitOrder.params["market_order_slippage_bps"]`.
269    #[builder(default = 50)]
270    pub market_order_slippage_bps: u32,
271    /// If true, attach Nautilus builder attribution to eligible mainnet orders.
272    #[builder(default = true)]
273    pub include_builder_attribution: bool,
274    /// WebSocket transport backend (`Sockudo` by default; `Tungstenite` when
275    /// the `transport-sockudo` feature is disabled).
276    #[builder(default)]
277    pub transport_backend: TransportBackend,
278    /// Timeout in seconds for WebSocket post trading requests.
279    #[builder(default = 10)]
280    pub ws_post_timeout_secs: u64,
281    /// Poll interval in seconds for `outcomeMeta` settlement detection.
282    /// Disabled by default; venue `Settlement` fills drive HIP-4 settlement
283    /// through the standard user-fills stream. Keep disabled: metadata inference
284    /// can emit closing fills for markets that are still trading.
285    #[builder(default = 0)]
286    pub outcome_settlement_poll_secs: u64,
287    /// Account-wide scheduled-cancel timeout in seconds, at least 15 when set.
288    /// Refreshes every third of the timeout while the execution WebSocket is active.
289    /// `None` leaves the venue schedule unchanged. Shutdown stops refreshing without clearing it.
290    pub scheduled_cancel_timeout_secs: Option<u64>,
291}
292
293#[cfg(feature = "python")]
294nautilus_core::impl_pyo3_config_getters!(HyperliquidExecutionClientConfig {
295    product_types: Vec<HyperliquidProductType>,
296    account_id: AccountId,
297    vault_address: Option<String>,
298    account_address: Option<String>,
299    environment: HyperliquidEnvironment,
300    base_url_http: Option<String>,
301    base_url_ws: Option<String>,
302    base_url_exchange: Option<String>,
303    http_timeout_secs: u64,
304    max_retries: u32,
305    retry_delay_initial_ms: u64,
306    retry_delay_max_ms: u64,
307    normalize_prices: bool,
308    market_order_slippage_bps: u32,
309    include_builder_attribution: bool,
310    ws_post_timeout_secs: u64,
311    transport_backend: TransportBackend,
312    scheduled_cancel_timeout_secs: Option<u64>,
313});
314
315impl Default for HyperliquidExecutionClientConfig {
316    fn default() -> Self {
317        Self::builder().build()
318    }
319}
320
321impl HyperliquidExecutionClientConfig {
322    pub(crate) fn validate(&self) -> anyhow::Result<()> {
323        anyhow::ensure!(
324            !self.product_types.is_empty(),
325            "Execution product_types must not be empty"
326        );
327
328        if let Some(timeout_secs) = self.scheduled_cancel_timeout_secs
329            && (timeout_secs < 15 || timeout_secs.checked_mul(1_000).is_none())
330        {
331            anyhow::bail!(
332                "scheduled_cancel_timeout_secs must be at least 15 and fit in milliseconds"
333            );
334        }
335
336        Ok(())
337    }
338
339    /// Returns `true` when private key is populated and non-empty.
340    #[must_use]
341    pub fn has_credentials(&self) -> bool {
342        self.private_key
343            .as_ref()
344            .map(SecretString::expose_secret)
345            .is_some_and(|s| !s.trim().is_empty())
346    }
347
348    /// Returns the WebSocket URL, respecting the environment and overrides.
349    #[must_use]
350    pub fn ws_url(&self) -> String {
351        self.base_url_ws
352            .clone()
353            .unwrap_or_else(|| ws_url(self.environment).to_string())
354    }
355
356    /// Returns the HTTP info URL, respecting the environment and overrides.
357    #[must_use]
358    pub fn http_url(&self) -> String {
359        self.base_url_http
360            .clone()
361            .unwrap_or_else(|| info_url(self.environment).to_string())
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use rstest::rstest;
368
369    use super::*;
370
371    #[rstest]
372    fn test_execution_product_scope_default_and_toml() {
373        let defaults = HyperliquidExecutionClientConfig::default();
374        assert_eq!(
375            defaults.product_types,
376            vec![
377                HyperliquidProductType::Perp,
378                HyperliquidProductType::Spot,
379                HyperliquidProductType::Outcome,
380            ]
381        );
382        let config: HyperliquidExecutionClientConfig =
383            toml::from_str("product_types = ['SPOT']").unwrap();
384        assert_eq!(config.product_types, vec![HyperliquidProductType::Spot]);
385        config.validate().unwrap();
386        let restored: HyperliquidExecutionClientConfig =
387            serde_json::from_str(&serde_json::to_string(&config).unwrap()).unwrap();
388        assert_eq!(restored.product_types, config.product_types);
389    }
390
391    #[rstest]
392    fn test_execution_product_scope_rejects_empty() {
393        let config = HyperliquidExecutionClientConfig::builder()
394            .product_types(vec![])
395            .build();
396        assert!(
397            config
398                .validate()
399                .unwrap_err()
400                .to_string()
401                .contains("must not be empty")
402        );
403    }
404
405    #[rstest]
406    fn data_book_feed_defaults_and_round_trips() {
407        let default: HyperliquidDataClientConfig = serde_json::from_str("{}").unwrap();
408        assert_eq!(default.book_feed, HyperliquidBookFeed::L2Book);
409        let compact: HyperliquidDataClientConfig =
410            serde_json::from_str(r#"{"book_feed":"l2"}"#).unwrap();
411        assert_eq!(compact.book_feed, HyperliquidBookFeed::L2);
412        assert_eq!(serde_json::to_value(compact).unwrap()["book_feed"], "l2");
413        assert!(
414            serde_json::from_str::<HyperliquidDataClientConfig>(r#"{"book_feed":"fast"}"#).is_err()
415        );
416    }
417
418    #[rstest]
419    #[case::disabled(None, true)]
420    #[case::zero(Some(0), false)]
421    #[case::too_short(Some(14), false)]
422    #[case::minimum(Some(15), true)]
423    #[case::normal(Some(60), true)]
424    #[case::overflow(Some(u64::MAX), false)]
425    fn test_exec_config_scheduled_cancel(#[case] timeout_secs: Option<u64>, #[case] valid: bool) {
426        let config = HyperliquidExecutionClientConfig {
427            scheduled_cancel_timeout_secs: timeout_secs,
428            ..Default::default()
429        };
430
431        let decoded: HyperliquidExecutionClientConfig =
432            serde_json::from_value(serde_json::to_value(&config).unwrap()).unwrap();
433        let result = config.validate();
434
435        assert_eq!(decoded.scheduled_cancel_timeout_secs, timeout_secs);
436        assert_eq!(result.is_ok(), valid);
437
438        if !valid {
439            assert_eq!(
440                result.unwrap_err().to_string(),
441                "scheduled_cancel_timeout_secs must be at least 15 and fit in milliseconds"
442            );
443        }
444    }
445
446    #[rstest]
447    fn test_exec_config_scheduled_cancel_default() {
448        let config = HyperliquidExecutionClientConfig::default();
449        assert_eq!(config.scheduled_cancel_timeout_secs, None);
450    }
451
452    #[rstest]
453    fn test_exec_config_default_account_address_is_none() {
454        let config = HyperliquidExecutionClientConfig::default();
455        assert!(config.account_address.is_none());
456    }
457
458    #[rstest]
459    fn test_exec_config_with_account_address() {
460        let config = HyperliquidExecutionClientConfig {
461            account_address: Some("0x1234".to_string()),
462            ..HyperliquidExecutionClientConfig::default()
463        };
464        assert_eq!(config.account_address.as_deref(), Some("0x1234"));
465    }
466
467    #[rstest]
468    fn test_data_config_toml_minimal() {
469        let config: HyperliquidDataClientConfig = toml::from_str(
470            r#"
471environment = "testnet"
472http_timeout_secs = 30
473update_instruments_interval_mins = 10
474transport_backend = "tungstenite"
475"#,
476        )
477        .unwrap();
478
479        assert_eq!(config.environment, HyperliquidEnvironment::Testnet);
480        assert_eq!(config.http_timeout_secs, 30);
481        assert_eq!(config.update_instruments_interval_mins, 10);
482        assert_eq!(config.transport_backend, TransportBackend::Tungstenite);
483        assert_eq!(config.stale_stream_receive_timeout_secs, 120);
484        assert_eq!(config.stream_health_check_interval_secs, 15);
485        assert_eq!(config.stale_stream_warning_cooldown_secs, 60);
486        assert!(!config.stale_stream_recovery_enabled);
487        assert_eq!(config.stale_stream_recovery_cooldown_secs, 120);
488        assert_eq!(config.stale_stream_max_targeted_resubscribes, 3);
489        assert_eq!(config.book_snapshot_timeout_secs, 10);
490    }
491
492    #[rstest]
493    fn test_data_config_toml_stale_stream_settings() {
494        let config: HyperliquidDataClientConfig = toml::from_str(
495            "
496stale_stream_receive_timeout_secs = 30
497stream_health_check_interval_secs = 5
498stale_stream_warning_cooldown_secs = 20
499stale_stream_recovery_enabled = true
500stale_stream_recovery_cooldown_secs = 45
501stale_stream_max_targeted_resubscribes = 5
502book_snapshot_timeout_secs = 4
503",
504        )
505        .unwrap();
506
507        assert_eq!(config.stale_stream_receive_timeout_secs, 30);
508        assert_eq!(config.stream_health_check_interval_secs, 5);
509        assert_eq!(config.stale_stream_warning_cooldown_secs, 20);
510        assert!(config.stale_stream_recovery_enabled);
511        assert_eq!(config.stale_stream_recovery_cooldown_secs, 45);
512        assert_eq!(config.stale_stream_max_targeted_resubscribes, 5);
513        assert_eq!(config.book_snapshot_timeout_secs, 4);
514    }
515
516    #[rstest]
517    fn test_exec_config_toml_empty_uses_defaults() {
518        let config: HyperliquidExecutionClientConfig = toml::from_str("").unwrap();
519        let expected = HyperliquidExecutionClientConfig::default();
520
521        assert_eq!(config.environment, expected.environment);
522        assert_eq!(config.http_timeout_secs, expected.http_timeout_secs);
523        assert_eq!(config.max_retries, expected.max_retries);
524        assert_eq!(config.normalize_prices, expected.normalize_prices);
525        assert_eq!(
526            config.market_order_slippage_bps,
527            expected.market_order_slippage_bps,
528        );
529        assert_eq!(
530            config.include_builder_attribution,
531            expected.include_builder_attribution,
532        );
533        assert_eq!(config.transport_backend, expected.transport_backend);
534        assert_eq!(config.ws_post_timeout_secs, expected.ws_post_timeout_secs);
535        assert_eq!(
536            config.outcome_settlement_poll_secs,
537            expected.outcome_settlement_poll_secs,
538        );
539    }
540
541    #[rstest]
542    fn test_exec_config_toml_include_builder_attribution_false() {
543        let config: HyperliquidExecutionClientConfig =
544            toml::from_str("include_builder_attribution = false").unwrap();
545
546        assert!(!config.include_builder_attribution);
547    }
548
549    #[rstest]
550    fn test_data_config_debug_redacts_private_key() {
551        let config = HyperliquidDataClientConfig {
552            private_key: Some(
553                "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(),
554            ),
555            ..HyperliquidDataClientConfig::default()
556        };
557        let debug = format!("{config:?}");
558
559        assert!(debug.contains(REDACTED));
560        assert!(!debug.contains("0123456789abcdef"));
561    }
562
563    #[rstest]
564    fn test_exec_config_debug_redacts_private_key() {
565        let config = HyperliquidExecutionClientConfig {
566            private_key: Some(
567                "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(),
568            ),
569            ..HyperliquidExecutionClientConfig::default()
570        };
571        let debug = format!("{config:?}");
572
573        assert!(debug.contains(REDACTED));
574        assert!(!debug.contains("0123456789abcdef"));
575    }
576}