Skip to main content

nautilus_hyperliquid/python/
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//! Python bindings for Hyperliquid configuration.
17
18use nautilus_core::{python::to_pyvalue_err, string::secret::SecretString};
19use nautilus_model::identifiers::AccountId;
20use nautilus_network::websocket::TransportBackend;
21use pyo3::prelude::*;
22
23use crate::{
24    common::enums::HyperliquidEnvironment,
25    config::{HyperliquidDataClientConfig, HyperliquidExecutionClientConfig},
26};
27
28#[pymethods]
29#[pyo3_stub_gen::derive::gen_stub_pymethods]
30impl HyperliquidDataClientConfig {
31    /// Configuration for the Hyperliquid data client.
32    ///
33    /// The `stale_stream_*` options control the stream health monitor. With recovery
34    /// enabled, a stale stream is warned about first, then acted on once per recovery
35    /// cooldown. A stale order book delta stream, including depth that shares its stream,
36    /// starts shared book recovery, which resubscribes until a fresh snapshot arrives.
37    /// Depth-only and BBO streams receive a targeted resubscribe (preserving the original
38    /// `l2Book` options) and escalate to a full WebSocket reconnect after
39    /// `stale_stream_max_targeted_resubscribes` failed attempts. Fresh data resets the ladder. See the Hyperliquid integration guide
40    /// ("Stream health and recovery") for details.
41    #[new]
42    #[pyo3(signature = (
43        environment = None,
44        private_key = None,
45        base_url_http = None,
46        base_url_ws = None,
47        proxy_url = None,
48        http_timeout_secs = None,
49        ws_timeout_secs = None,
50        update_instruments_interval_mins = None,
51        transport_backend = None,
52        stale_stream_receive_timeout_secs = None,
53        stream_health_check_interval_secs = None,
54        stale_stream_warning_cooldown_secs = None,
55        stale_stream_recovery_enabled = None,
56        stale_stream_recovery_cooldown_secs = None,
57        stale_stream_max_targeted_resubscribes = None,
58        book_snapshot_timeout_secs = None,
59        book_feed = None,
60    ))]
61    #[expect(clippy::too_many_arguments)]
62    fn py_new(
63        environment: Option<HyperliquidEnvironment>,
64        private_key: Option<String>,
65        base_url_http: Option<String>,
66        base_url_ws: Option<String>,
67        proxy_url: Option<String>,
68        http_timeout_secs: Option<u64>,
69        ws_timeout_secs: Option<u64>,
70        update_instruments_interval_mins: Option<u64>,
71        transport_backend: Option<TransportBackend>,
72        stale_stream_receive_timeout_secs: Option<u64>,
73        stream_health_check_interval_secs: Option<u64>,
74        stale_stream_warning_cooldown_secs: Option<u64>,
75        stale_stream_recovery_enabled: Option<bool>,
76        stale_stream_recovery_cooldown_secs: Option<u64>,
77        stale_stream_max_targeted_resubscribes: Option<u32>,
78        book_snapshot_timeout_secs: Option<u64>,
79        book_feed: Option<String>,
80    ) -> PyResult<Self> {
81        let defaults = Self::default();
82        let book_feed = book_feed
83            .map(|value| value.parse())
84            .transpose()
85            .map_err(|_| to_pyvalue_err("book_feed must be 'l2Book' or 'l2'"))?
86            .unwrap_or(defaults.book_feed);
87
88        Ok(Self {
89            private_key: private_key.map(SecretString::from),
90            base_url_http,
91            base_url_ws,
92            book_feed,
93            proxy_url: proxy_url.map(SecretString::from),
94            environment: environment.unwrap_or(defaults.environment),
95            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
96            ws_timeout_secs: ws_timeout_secs.unwrap_or(defaults.ws_timeout_secs),
97            stale_stream_receive_timeout_secs: stale_stream_receive_timeout_secs
98                .unwrap_or(defaults.stale_stream_receive_timeout_secs),
99            stream_health_check_interval_secs: stream_health_check_interval_secs
100                .unwrap_or(defaults.stream_health_check_interval_secs),
101            stale_stream_warning_cooldown_secs: stale_stream_warning_cooldown_secs
102                .unwrap_or(defaults.stale_stream_warning_cooldown_secs),
103            stale_stream_recovery_enabled: stale_stream_recovery_enabled
104                .unwrap_or(defaults.stale_stream_recovery_enabled),
105            stale_stream_recovery_cooldown_secs: stale_stream_recovery_cooldown_secs
106                .unwrap_or(defaults.stale_stream_recovery_cooldown_secs),
107            stale_stream_max_targeted_resubscribes: stale_stream_max_targeted_resubscribes
108                .unwrap_or(defaults.stale_stream_max_targeted_resubscribes),
109            book_snapshot_timeout_secs: book_snapshot_timeout_secs
110                .unwrap_or(defaults.book_snapshot_timeout_secs),
111            update_instruments_interval_mins: update_instruments_interval_mins
112                .unwrap_or(defaults.update_instruments_interval_mins),
113            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
114        })
115    }
116
117    /// The fixed venue order book source.
118    #[getter]
119    fn book_feed(&self) -> &str {
120        self.book_feed.as_ref()
121    }
122
123    #[getter]
124    const fn has_proxy_url(&self) -> bool {
125        self.proxy_url.is_some()
126    }
127
128    fn __repr__(&self) -> String {
129        stringify!(HyperliquidDataClientConfig).to_string()
130    }
131}
132
133#[pymethods]
134#[pyo3_stub_gen::derive::gen_stub_pymethods]
135impl HyperliquidExecutionClientConfig {
136    /// Configuration for the Hyperliquid execution client.
137    #[new]
138    #[pyo3(signature = (
139        account_id = None,
140        private_key = None,
141        vault_address = None,
142        account_address = None,
143        environment = None,
144        base_url_http = None,
145        base_url_ws = None,
146        base_url_exchange = None,
147        proxy_url = None,
148        http_timeout_secs = None,
149        max_retries = None,
150        retry_delay_initial_ms = None,
151        retry_delay_max_ms = None,
152        normalize_prices = None,
153        market_order_slippage_bps = None,
154        include_builder_attribution = None,
155        ws_post_timeout_secs = None,
156        transport_backend = None,
157        scheduled_cancel_timeout_secs = None,
158        product_types = None,
159    ))]
160    #[expect(clippy::too_many_arguments)]
161    fn py_new(
162        account_id: Option<AccountId>,
163        private_key: Option<String>,
164        vault_address: Option<String>,
165        account_address: Option<String>,
166        environment: Option<HyperliquidEnvironment>,
167        base_url_http: Option<String>,
168        base_url_ws: Option<String>,
169        base_url_exchange: Option<String>,
170        proxy_url: Option<String>,
171        http_timeout_secs: Option<u64>,
172        max_retries: Option<u32>,
173        retry_delay_initial_ms: Option<u64>,
174        retry_delay_max_ms: Option<u64>,
175        normalize_prices: Option<bool>,
176        market_order_slippage_bps: Option<u32>,
177        include_builder_attribution: Option<bool>,
178        ws_post_timeout_secs: Option<u64>,
179        transport_backend: Option<TransportBackend>,
180        scheduled_cancel_timeout_secs: Option<u64>,
181        product_types: Option<Vec<crate::common::enums::HyperliquidProductType>>,
182    ) -> Self {
183        let defaults = Self::default();
184        Self {
185            account_id: account_id.unwrap_or(defaults.account_id),
186            private_key: private_key.map(SecretString::from),
187            vault_address,
188            account_address,
189            base_url_http,
190            base_url_ws,
191            base_url_exchange,
192            proxy_url: proxy_url.map(SecretString::from),
193            environment: environment.unwrap_or(defaults.environment),
194            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
195            max_retries: max_retries.unwrap_or(defaults.max_retries),
196            retry_delay_initial_ms: retry_delay_initial_ms
197                .unwrap_or(defaults.retry_delay_initial_ms),
198            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
199            normalize_prices: normalize_prices.unwrap_or(defaults.normalize_prices),
200            market_order_slippage_bps: market_order_slippage_bps
201                .unwrap_or(defaults.market_order_slippage_bps),
202            include_builder_attribution: include_builder_attribution
203                .unwrap_or(defaults.include_builder_attribution),
204            ws_post_timeout_secs: ws_post_timeout_secs.unwrap_or(defaults.ws_post_timeout_secs),
205            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
206            outcome_settlement_poll_secs: defaults.outcome_settlement_poll_secs,
207            scheduled_cancel_timeout_secs,
208            product_types: product_types.unwrap_or(defaults.product_types),
209        }
210    }
211
212    #[getter]
213    const fn has_proxy_url(&self) -> bool {
214        self.proxy_url.is_some()
215    }
216
217    fn __repr__(&self) -> String {
218        stringify!(HyperliquidExecutionClientConfig).to_string()
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use pyo3::types::PyDict;
225    use rstest::rstest;
226
227    use super::*;
228
229    #[rstest]
230    #[case::default(None)]
231    #[case::enabled(Some(60))]
232    fn test_python_scheduled_cancel(#[case] timeout_secs: Option<u64>) {
233        Python::initialize();
234        Python::attach(|py| {
235            let kwargs = PyDict::new(py);
236            if let Some(timeout_secs) = timeout_secs {
237                kwargs
238                    .set_item("scheduled_cancel_timeout_secs", timeout_secs)
239                    .unwrap();
240            }
241
242            let config = py
243                .get_type::<HyperliquidExecutionClientConfig>()
244                .call((), Some(&kwargs))
245                .unwrap();
246            let getter = config
247                .getattr("scheduled_cancel_timeout_secs")
248                .unwrap()
249                .extract::<Option<u64>>()
250                .unwrap();
251            let rust_config = config
252                .extract::<PyRef<HyperliquidExecutionClientConfig>>()
253                .unwrap();
254
255            assert_eq!(getter, timeout_secs);
256            assert_eq!(rust_config.scheduled_cancel_timeout_secs, timeout_secs);
257        });
258    }
259}