nautilus-hyperliquid 0.55.0

Hyperliquid integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

use std::collections::HashMap;

use nautilus_core::python::{IntoPyObjectNautilusExt, to_pyvalue_err};
use nautilus_model::{
    data::BarType,
    enums::{OrderSide, OrderType, TimeInForce},
    identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
    instruments::Instrument,
    orders::OrderAny,
    python::{
        instruments::{instrument_any_to_pyobject, pyobject_to_instrument_any},
        orders::pyobject_to_order_any,
    },
    types::{Price, Quantity},
};
use pyo3::{prelude::*, types::PyList};
use serde_json::to_string;

use crate::http::{client::HyperliquidHttpClient, parse::HyperliquidMarketType};

#[pymethods]
#[pyo3_stub_gen::derive::gen_stub_pymethods]
impl HyperliquidHttpClient {
    /// Provides a high-level HTTP client for the [Hyperliquid](https://hyperliquid.xyz/) REST API.
    ///
    /// This domain client wraps `HyperliquidRawHttpClient` and provides methods that work
    /// with Nautilus domain types. It maintains an instrument cache and handles conversions
    /// between Hyperliquid API responses and Nautilus domain models.
    #[new]
    #[pyo3(signature = (private_key=None, vault_address=None, account_address=None, is_testnet=false, timeout_secs=60, proxy_url=None, normalize_prices=true))]
    fn py_new(
        private_key: Option<String>,
        vault_address: Option<String>,
        account_address: Option<String>,
        is_testnet: bool,
        timeout_secs: u64,
        proxy_url: Option<String>,
        normalize_prices: bool,
    ) -> PyResult<Self> {
        let mut client = Self::with_credentials(
            private_key,
            vault_address,
            account_address,
            is_testnet,
            timeout_secs,
            proxy_url,
        )
        .map_err(to_pyvalue_err)?;
        client.set_normalize_prices(normalize_prices);
        Ok(client)
    }

    /// Creates an authenticated client from environment variables for the specified network.
    ///
    /// # Errors
    ///
    /// Returns `Error.Auth` if required environment variables are not set.
    #[staticmethod]
    #[pyo3(name = "from_env", signature = (is_testnet=false))]
    fn py_from_env(is_testnet: bool) -> PyResult<Self> {
        Self::from_env(is_testnet).map_err(to_pyvalue_err)
    }

    /// Creates a new `HyperliquidHttpClient` configured with explicit credentials.
    #[staticmethod]
    #[pyo3(name = "from_credentials", signature = (private_key, vault_address=None, is_testnet=false, timeout_secs=60, proxy_url=None))]
    fn py_from_credentials(
        private_key: &str,
        vault_address: Option<&str>,
        is_testnet: bool,
        timeout_secs: u64,
        proxy_url: Option<String>,
    ) -> PyResult<Self> {
        Self::from_credentials(
            private_key,
            vault_address,
            is_testnet,
            timeout_secs,
            proxy_url,
        )
        .map_err(to_pyvalue_err)
    }

    /// Caches a single instrument.
    ///
    /// This is required for parsing orders, fills, and positions into reports.
    /// Any existing instrument with the same symbol will be replaced.
    #[pyo3(name = "cache_instrument")]
    fn py_cache_instrument(&self, py: Python<'_>, instrument: Py<PyAny>) -> PyResult<()> {
        self.cache_instrument(&pyobject_to_instrument_any(py, instrument)?);
        Ok(())
    }

    /// Set the account ID for this client.
    ///
    /// This is required for generating reports with the correct account ID.
    #[pyo3(name = "set_account_id")]
    fn py_set_account_id(&mut self, account_id: &str) {
        let account_id = AccountId::from(account_id);
        self.set_account_id(account_id);
    }

    /// Gets the user address derived from the private key (if client has credentials).
    ///
    /// # Errors
    ///
    /// Returns `Error.Auth` if the client has no signer configured.
    #[pyo3(name = "get_user_address")]
    fn py_get_user_address(&self) -> PyResult<String> {
        self.get_user_address().map_err(to_pyvalue_err)
    }

    /// Get mapping from spot fill coin identifiers to instrument symbols.
    ///
    /// Hyperliquid WebSocket fills for spot use `@{pair_index}` format (e.g., `@107`),
    /// while instruments are identified by full symbols (e.g., `HYPE-USDC-SPOT`).
    /// This mapping allows looking up the instrument from a spot fill.
    ///
    /// This method also caches the mapping internally for use by fill parsing methods.
    #[pyo3(name = "get_spot_fill_coin_mapping")]
    fn py_get_spot_fill_coin_mapping(&self) -> HashMap<String, String> {
        self.get_spot_fill_coin_mapping()
            .into_iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    /// Get spot metadata (internal helper).
    #[pyo3(name = "get_spot_meta")]
    fn py_get_spot_meta<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let meta = client.get_spot_meta().await.map_err(to_pyvalue_err)?;
            to_string(&meta).map_err(to_pyvalue_err)
        })
    }

    #[pyo3(name = "get_perp_meta")]
    fn py_get_perp_meta<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let meta = client.load_perp_meta().await.map_err(to_pyvalue_err)?;
            to_string(&meta).map_err(to_pyvalue_err)
        })
    }

    #[pyo3(name = "load_instrument_definitions", signature = (include_spot=true, include_perps=true, include_perps_hip3=false))]
    fn py_load_instrument_definitions<'py>(
        &self,
        py: Python<'py>,
        include_spot: bool,
        include_perps: bool,
        include_perps_hip3: bool,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let mut defs = client
                .request_instrument_defs()
                .await
                .map_err(to_pyvalue_err)?;

            defs.retain(|def| match def.market_type {
                HyperliquidMarketType::Perp => {
                    if def.is_hip3 {
                        include_perps_hip3
                    } else {
                        include_perps
                    }
                }
                HyperliquidMarketType::Spot => include_spot,
            });

            let mut instruments = client.convert_defs(defs);
            instruments.sort_by_key(|instrument| instrument.id());

            Python::attach(|py| {
                let mut py_instruments = Vec::with_capacity(instruments.len());
                for instrument in instruments {
                    py_instruments.push(instrument_any_to_pyobject(py, instrument)?);
                }

                let py_list = PyList::new(py, &py_instruments)?;
                Ok(py_list.into_any().unbind())
            })
        })
    }

    #[pyo3(name = "request_quote_ticks", signature = (instrument_id, start=None, end=None, limit=None))]
    fn py_request_quote_ticks<'py>(
        &self,
        py: Python<'py>,
        instrument_id: InstrumentId,
        start: Option<chrono::DateTime<chrono::Utc>>,
        end: Option<chrono::DateTime<chrono::Utc>>,
        limit: Option<u32>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let _ = (instrument_id, start, end, limit);
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            Err::<Vec<u8>, _>(to_pyvalue_err(anyhow::anyhow!(
                "Hyperliquid does not provide historical quotes via HTTP API"
            )))
        })
    }

    #[pyo3(name = "request_trade_ticks", signature = (instrument_id, start=None, end=None, limit=None))]
    fn py_request_trade_ticks<'py>(
        &self,
        py: Python<'py>,
        instrument_id: InstrumentId,
        start: Option<chrono::DateTime<chrono::Utc>>,
        end: Option<chrono::DateTime<chrono::Utc>>,
        limit: Option<u32>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let _ = (instrument_id, start, end, limit);
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            Err::<Vec<u8>, _>(to_pyvalue_err(anyhow::anyhow!(
                "Hyperliquid does not provide historical market trades via HTTP API"
            )))
        })
    }

    /// Request historical bars for an instrument.
    ///
    /// Fetches candle data from the Hyperliquid API and converts it to Nautilus bars.
    /// Incomplete bars (where end_timestamp >= current time) are filtered out.
    ///
    /// # References
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candles-snapshot>
    #[pyo3(name = "request_bars", signature = (bar_type, start=None, end=None, limit=None))]
    fn py_request_bars<'py>(
        &self,
        py: Python<'py>,
        bar_type: BarType,
        start: Option<chrono::DateTime<chrono::Utc>>,
        end: Option<chrono::DateTime<chrono::Utc>>,
        limit: Option<u32>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let bars = client
                .request_bars(bar_type, start, end, limit)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let pylist = PyList::new(py, bars.into_iter().map(|b| b.into_py_any_unwrap(py)))?;
                Ok(pylist.into_py_any_unwrap(py))
            })
        })
    }

    /// Submits an order to the exchange.
    #[pyo3(name = "submit_order", signature = (
        instrument_id,
        client_order_id,
        order_side,
        order_type,
        quantity,
        time_in_force,
        price=None,
        trigger_price=None,
        post_only=false,
        reduce_only=false,
    ))]
    #[allow(clippy::too_many_arguments)]
    fn py_submit_order<'py>(
        &self,
        py: Python<'py>,
        instrument_id: InstrumentId,
        client_order_id: ClientOrderId,
        order_side: OrderSide,
        order_type: OrderType,
        quantity: Quantity,
        time_in_force: TimeInForce,
        price: Option<Price>,
        trigger_price: Option<Price>,
        post_only: bool,
        reduce_only: bool,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let report = client
                .submit_order(
                    instrument_id,
                    client_order_id,
                    order_side,
                    order_type,
                    quantity,
                    time_in_force,
                    price,
                    trigger_price,
                    post_only,
                    reduce_only,
                )
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| Ok(report.into_py_any_unwrap(py)))
        })
    }

    /// Cancel an order on the Hyperliquid exchange.
    ///
    /// Can cancel either by venue order ID or client order ID.
    /// At least one ID must be provided.
    #[pyo3(name = "cancel_order", signature = (
        instrument_id,
        client_order_id=None,
        venue_order_id=None,
    ))]
    fn py_cancel_order<'py>(
        &self,
        py: Python<'py>,
        instrument_id: InstrumentId,
        client_order_id: Option<ClientOrderId>,
        venue_order_id: Option<VenueOrderId>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            client
                .cancel_order(instrument_id, client_order_id, venue_order_id)
                .await
                .map_err(to_pyvalue_err)?;
            Ok(())
        })
    }

    /// Modify an order on the Hyperliquid exchange.
    ///
    /// The HL modify API requires a full replacement order spec plus the
    /// venue order ID. The caller must provide all order fields.
    #[pyo3(name = "modify_order")]
    #[allow(clippy::too_many_arguments)]
    fn py_modify_order<'py>(
        &self,
        py: Python<'py>,
        instrument_id: InstrumentId,
        venue_order_id: VenueOrderId,
        order_side: OrderSide,
        order_type: OrderType,
        price: Price,
        quantity: Quantity,
        trigger_price: Option<Price>,
        reduce_only: bool,
        post_only: bool,
        time_in_force: TimeInForce,
        client_order_id: Option<ClientOrderId>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            client
                .modify_order(
                    instrument_id,
                    venue_order_id,
                    order_side,
                    order_type,
                    price,
                    quantity,
                    trigger_price,
                    reduce_only,
                    post_only,
                    time_in_force,
                    client_order_id,
                )
                .await
                .map_err(to_pyvalue_err)?;
            Ok(())
        })
    }

    /// Submit multiple orders to the Hyperliquid exchange in a single request.
    #[pyo3(name = "submit_orders")]
    fn py_submit_orders<'py>(
        &self,
        py: Python<'py>,
        orders: Vec<Py<PyAny>>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let order_anys: Vec<OrderAny> = Python::attach(|py| {
                orders
                    .into_iter()
                    .map(|order| pyobject_to_order_any(py, order))
                    .collect::<PyResult<Vec<_>>>()
                    .map_err(to_pyvalue_err)
            })?;

            let order_refs: Vec<&OrderAny> = order_anys.iter().collect();

            let reports = client
                .submit_orders(&order_refs)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let pylist =
                    PyList::new(py, reports.into_iter().map(|r| r.into_py_any_unwrap(py)))?;
                Ok(pylist.into_py_any_unwrap(py))
            })
        })
    }

    /// Request order status reports for a user.
    ///
    /// Fetches open orders via `info_frontend_open_orders` and parses them into OrderStatusReports.
    /// This method requires instruments to be added to the client cache via `cache_instrument()`.
    ///
    /// For vault tokens (starting with "vntls:") that are not in the cache, synthetic instruments
    /// will be created automatically.
    #[pyo3(name = "request_order_status_reports")]
    fn py_request_order_status_reports<'py>(
        &self,
        py: Python<'py>,
        instrument_id: Option<&str>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();
        let instrument_id = instrument_id.map(InstrumentId::from);

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let account_address = client.get_account_address().map_err(to_pyvalue_err)?;
            let reports = client
                .request_order_status_reports(&account_address, instrument_id)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let pylist =
                    PyList::new(py, reports.into_iter().map(|r| r.into_py_any_unwrap(py)))?;
                Ok(pylist.into_py_any_unwrap(py))
            })
        })
    }

    /// Request fill reports for a user.
    ///
    /// Fetches user fills via `info_user_fills` and parses them into FillReports.
    /// This method requires instruments to be added to the client cache via `cache_instrument()`.
    ///
    /// For vault tokens (starting with "vntls:") that are not in the cache, synthetic instruments
    /// will be created automatically.
    #[pyo3(name = "request_fill_reports")]
    fn py_request_fill_reports<'py>(
        &self,
        py: Python<'py>,
        instrument_id: Option<&str>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();
        let instrument_id = instrument_id.map(InstrumentId::from);

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let account_address = client.get_account_address().map_err(to_pyvalue_err)?;
            let reports = client
                .request_fill_reports(&account_address, instrument_id)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let pylist =
                    PyList::new(py, reports.into_iter().map(|r| r.into_py_any_unwrap(py)))?;
                Ok(pylist.into_py_any_unwrap(py))
            })
        })
    }

    /// Request position status reports for a user.
    ///
    /// Fetches clearinghouse state via `info_clearinghouse_state` and parses positions into PositionStatusReports.
    /// This method requires instruments to be added to the client cache via `cache_instrument()`.
    ///
    /// For vault tokens (starting with "vntls:") that are not in the cache, synthetic instruments
    /// will be created automatically.
    #[pyo3(name = "request_position_status_reports")]
    fn py_request_position_status_reports<'py>(
        &self,
        py: Python<'py>,
        instrument_id: Option<&str>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();
        let instrument_id = instrument_id.map(InstrumentId::from);

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let account_address = client.get_account_address().map_err(to_pyvalue_err)?;
            let reports = client
                .request_position_status_reports(&account_address, instrument_id)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let pylist =
                    PyList::new(py, reports.into_iter().map(|r| r.into_py_any_unwrap(py)))?;
                Ok(pylist.into_py_any_unwrap(py))
            })
        })
    }

    /// Request account state (balances and margins) for a user.
    ///
    /// Fetches clearinghouse state from Hyperliquid API and converts it to `AccountState`.
    ///
    /// # Errors
    ///
    /// Returns an error if `account_id` is not set or the API request fails.
    #[pyo3(name = "request_account_state")]
    fn py_request_account_state<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let account_address = client.get_account_address().map_err(to_pyvalue_err)?;
            let account_state = client
                .request_account_state(&account_address)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| Ok(account_state.into_py_any_unwrap(py)))
        })
    }

    /// Get user fee schedule and effective rates.
    #[pyo3(name = "info_user_fees")]
    fn py_info_user_fees<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let account_address = client.get_account_address().map_err(to_pyvalue_err)?;
            let json = client
                .info_user_fees(&account_address)
                .await
                .map_err(to_pyvalue_err)?;
            to_string(&json).map_err(to_pyvalue_err)
        })
    }
}