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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
// -------------------------------------------------------------------------------------------------
//  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 serde::Serialize;

use crate::{
    common::enums::{HyperliquidBarInterval, HyperliquidInfoRequestType},
    http::models::{
        HyperliquidExecBuilderFee, HyperliquidExecCancelByCloidRequest, HyperliquidExecGrouping,
        HyperliquidExecModifyOrderRequest, HyperliquidExecPlaceOrderRequest,
    },
};

/// Exchange action types for Hyperliquid.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ExchangeActionType {
    /// Place orders
    Order,
    /// Cancel orders by order ID
    Cancel,
    /// Cancel orders by client order ID
    CancelByCloid,
    /// Modify an existing order
    Modify,
    /// Update leverage for an asset
    UpdateLeverage,
    /// Update isolated margin for an asset
    UpdateIsolatedMargin,
}

impl AsRef<str> for ExchangeActionType {
    fn as_ref(&self) -> &str {
        match self {
            Self::Order => "order",
            Self::Cancel => "cancel",
            Self::CancelByCloid => "cancelByCloid",
            Self::Modify => "modify",
            Self::UpdateLeverage => "updateLeverage",
            Self::UpdateIsolatedMargin => "updateIsolatedMargin",
        }
    }
}

/// Parameters for placing orders.
#[derive(Debug, Clone, Serialize)]
pub struct OrderParams {
    pub orders: Vec<HyperliquidExecPlaceOrderRequest>,
    pub grouping: HyperliquidExecGrouping,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub builder: Option<HyperliquidExecBuilderFee>,
}

/// Parameters for canceling orders.
#[derive(Debug, Clone, Serialize)]
pub struct CancelParams {
    pub cancels: Vec<HyperliquidExecCancelByCloidRequest>,
}

/// Parameters for modifying an order.
#[derive(Debug, Clone, Serialize)]
pub struct ModifyParams {
    #[serde(flatten)]
    pub request: HyperliquidExecModifyOrderRequest,
}

/// Parameters for updating leverage.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateLeverageParams {
    pub asset: u32,
    pub is_cross: bool,
    pub leverage: u32,
}

/// Parameters for updating isolated margin.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateIsolatedMarginParams {
    pub asset: u32,
    pub is_buy: bool,
    pub ntli: i64,
}

/// Parameters for L2 book request.
#[derive(Debug, Clone, Serialize)]
pub struct L2BookParams {
    pub coin: String,
}

/// Parameters for user fills request.
#[derive(Debug, Clone, Serialize)]
pub struct UserFillsParams {
    pub user: String,
}

/// Parameters for order status request.
#[derive(Debug, Clone, Serialize)]
pub struct OrderStatusParams {
    pub user: String,
    pub oid: u64,
}

/// Parameters for open orders request.
#[derive(Debug, Clone, Serialize)]
pub struct OpenOrdersParams {
    pub user: String,
}

/// Parameters for clearinghouse state request.
#[derive(Debug, Clone, Serialize)]
pub struct ClearinghouseStateParams {
    pub user: String,
}

/// Parameters for candle snapshot request.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CandleSnapshotReq {
    pub coin: String,
    pub interval: HyperliquidBarInterval,
    pub start_time: u64,
    pub end_time: u64,
}

/// Wrapper for candle snapshot parameters.
#[derive(Debug, Clone, Serialize)]
pub struct CandleSnapshotParams {
    pub req: CandleSnapshotReq,
}

/// Info request parameters.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum InfoRequestParams {
    L2Book(L2BookParams),
    UserFills(UserFillsParams),
    OrderStatus(OrderStatusParams),
    OpenOrders(OpenOrdersParams),
    ClearinghouseState(ClearinghouseStateParams),
    CandleSnapshot(CandleSnapshotParams),
    None,
}

/// Represents an info request wrapper for `POST /info`.
#[derive(Debug, Clone, Serialize)]
pub struct InfoRequest {
    #[serde(rename = "type")]
    pub request_type: HyperliquidInfoRequestType,
    #[serde(flatten)]
    pub params: InfoRequestParams,
}

impl InfoRequest {
    /// Creates a request to get metadata about available markets.
    pub fn meta() -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::Meta,
            params: InfoRequestParams::None,
        }
    }

    /// Creates a request to get metadata for all perp dexes (standard + HIP-3).
    pub fn all_perp_metas() -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::AllPerpMetas,
            params: InfoRequestParams::None,
        }
    }

    /// Creates a request to get spot metadata (tokens and pairs).
    pub fn spot_meta() -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::SpotMeta,
            params: InfoRequestParams::None,
        }
    }

    /// Creates a request to get metadata with asset contexts (for price precision).
    pub fn meta_and_asset_ctxs() -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::MetaAndAssetCtxs,
            params: InfoRequestParams::None,
        }
    }

    /// Creates a request to get spot metadata with asset contexts.
    pub fn spot_meta_and_asset_ctxs() -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::SpotMetaAndAssetCtxs,
            params: InfoRequestParams::None,
        }
    }

    /// Creates a request to get L2 order book for a coin.
    pub fn l2_book(coin: &str) -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::L2Book,
            params: InfoRequestParams::L2Book(L2BookParams {
                coin: coin.to_string(),
            }),
        }
    }

    /// Creates a request to get user fills.
    pub fn user_fills(user: &str) -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::UserFills,
            params: InfoRequestParams::UserFills(UserFillsParams {
                user: user.to_string(),
            }),
        }
    }

    /// Creates a request to get order status for a user.
    pub fn order_status(user: &str, oid: u64) -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::OrderStatus,
            params: InfoRequestParams::OrderStatus(OrderStatusParams {
                user: user.to_string(),
                oid,
            }),
        }
    }

    /// Creates a request to get all open orders for a user.
    pub fn open_orders(user: &str) -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::OpenOrders,
            params: InfoRequestParams::OpenOrders(OpenOrdersParams {
                user: user.to_string(),
            }),
        }
    }

    /// Creates a request to get frontend open orders (includes more detail).
    pub fn frontend_open_orders(user: &str) -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::FrontendOpenOrders,
            params: InfoRequestParams::OpenOrders(OpenOrdersParams {
                user: user.to_string(),
            }),
        }
    }

    /// Creates a request to get user state (balances, positions, margin).
    pub fn clearinghouse_state(user: &str) -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::ClearinghouseState,
            params: InfoRequestParams::ClearinghouseState(ClearinghouseStateParams {
                user: user.to_string(),
            }),
        }
    }

    /// Creates a request to get user fee schedule and effective rates.
    pub fn user_fees(user: &str) -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::UserFees,
            params: InfoRequestParams::OpenOrders(OpenOrdersParams {
                user: user.to_string(),
            }),
        }
    }

    /// Creates a request to get candle/bar data.
    pub fn candle_snapshot(
        coin: &str,
        interval: HyperliquidBarInterval,
        start_time: u64,
        end_time: u64,
    ) -> Self {
        Self {
            request_type: HyperliquidInfoRequestType::CandleSnapshot,
            params: InfoRequestParams::CandleSnapshot(CandleSnapshotParams {
                req: CandleSnapshotReq {
                    coin: coin.to_string(),
                    interval,
                    start_time,
                    end_time,
                },
            }),
        }
    }
}

/// Exchange action parameters.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum ExchangeActionParams {
    Order(OrderParams),
    Cancel(CancelParams),
    Modify(ModifyParams),
    UpdateLeverage(UpdateLeverageParams),
    UpdateIsolatedMargin(UpdateIsolatedMarginParams),
}

/// Represents an exchange action wrapper for `POST /exchange`.
#[derive(Debug, Clone, Serialize)]
pub struct ExchangeAction {
    #[serde(rename = "type", serialize_with = "serialize_action_type")]
    pub action_type: ExchangeActionType,
    #[serde(flatten)]
    pub params: ExchangeActionParams,
}

fn serialize_action_type<S>(
    action_type: &ExchangeActionType,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(action_type.as_ref())
}

impl ExchangeAction {
    /// Creates an action to place orders with builder attribution.
    pub fn order(
        orders: Vec<HyperliquidExecPlaceOrderRequest>,
        builder: Option<HyperliquidExecBuilderFee>,
    ) -> Self {
        Self {
            action_type: ExchangeActionType::Order,
            params: ExchangeActionParams::Order(OrderParams {
                orders,
                grouping: HyperliquidExecGrouping::Na,
                builder,
            }),
        }
    }

    /// Creates an action to cancel orders.
    pub fn cancel(cancels: Vec<HyperliquidExecCancelByCloidRequest>) -> Self {
        Self {
            action_type: ExchangeActionType::Cancel,
            params: ExchangeActionParams::Cancel(CancelParams { cancels }),
        }
    }

    /// Creates an action to cancel orders by client order ID.
    pub fn cancel_by_cloid(cancels: Vec<HyperliquidExecCancelByCloidRequest>) -> Self {
        Self {
            action_type: ExchangeActionType::CancelByCloid,
            params: ExchangeActionParams::Cancel(CancelParams { cancels }),
        }
    }

    /// Creates an action to modify an order.
    pub fn modify(request: HyperliquidExecModifyOrderRequest) -> Self {
        Self {
            action_type: ExchangeActionType::Modify,
            params: ExchangeActionParams::Modify(ModifyParams { request }),
        }
    }

    /// Creates an action to update leverage for an asset.
    pub fn update_leverage(asset: u32, is_cross: bool, leverage: u32) -> Self {
        Self {
            action_type: ExchangeActionType::UpdateLeverage,
            params: ExchangeActionParams::UpdateLeverage(UpdateLeverageParams {
                asset,
                is_cross,
                leverage,
            }),
        }
    }

    /// Creates an action to update isolated margin for an asset.
    pub fn update_isolated_margin(asset: u32, is_buy: bool, ntli: i64) -> Self {
        Self {
            action_type: ExchangeActionType::UpdateIsolatedMargin,
            params: ExchangeActionParams::UpdateIsolatedMargin(UpdateIsolatedMarginParams {
                asset,
                is_buy,
                ntli,
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use rust_decimal::Decimal;

    use super::*;
    use crate::http::models::{
        Cloid, HyperliquidExecCancelByCloidRequest, HyperliquidExecLimitParams,
        HyperliquidExecModifyOrderRequest, HyperliquidExecOrderKind,
        HyperliquidExecPlaceOrderRequest, HyperliquidExecTif,
    };

    #[rstest]
    fn test_info_request_meta() {
        let req = InfoRequest::meta();

        assert_eq!(req.request_type, HyperliquidInfoRequestType::Meta);
        assert!(matches!(req.params, InfoRequestParams::None));
    }

    #[rstest]
    fn test_info_request_all_perp_metas() {
        let req = InfoRequest::all_perp_metas();

        assert_eq!(req.request_type, HyperliquidInfoRequestType::AllPerpMetas);
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains(r#""type":"allPerpMetas""#));
    }

    #[rstest]
    fn test_info_request_l2_book() {
        let req = InfoRequest::l2_book("BTC");

        assert_eq!(req.request_type, HyperliquidInfoRequestType::L2Book);
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("\"coin\":\"BTC\""));
    }

    #[rstest]
    fn test_exchange_action_order() {
        let order = HyperliquidExecPlaceOrderRequest {
            asset: 0,
            is_buy: true,
            price: Decimal::new(50000, 0),
            size: Decimal::new(1, 0),
            reduce_only: false,
            kind: HyperliquidExecOrderKind::Limit {
                limit: HyperliquidExecLimitParams {
                    tif: HyperliquidExecTif::Gtc,
                },
            },
            cloid: None,
        };

        let action = ExchangeAction::order(vec![order], None);

        assert_eq!(action.action_type, ExchangeActionType::Order);
        let json = serde_json::to_string(&action).unwrap();
        assert!(json.contains("\"orders\""));
    }

    #[rstest]
    fn test_exchange_action_cancel() {
        let cancel = HyperliquidExecCancelByCloidRequest {
            asset: 0,
            cloid: Cloid::from_hex("0x00000000000000000000000000000000").unwrap(),
        };

        let action = ExchangeAction::cancel(vec![cancel]);

        assert_eq!(action.action_type, ExchangeActionType::Cancel);
    }

    #[rstest]
    fn test_exchange_action_serialization() {
        let order = HyperliquidExecPlaceOrderRequest {
            asset: 0,
            is_buy: true,
            price: Decimal::new(50000, 0),
            size: Decimal::new(1, 0),
            reduce_only: false,
            kind: HyperliquidExecOrderKind::Limit {
                limit: HyperliquidExecLimitParams {
                    tif: HyperliquidExecTif::Gtc,
                },
            },
            cloid: None,
        };

        let action = ExchangeAction::order(vec![order], None);

        let json = serde_json::to_string(&action).unwrap();
        // Verify that action_type is serialized as "type" with the correct string value
        assert!(json.contains(r#""type":"order""#));
        assert!(json.contains(r#""orders""#));
        assert!(json.contains(r#""grouping":"na""#));
    }

    #[rstest]
    fn test_exchange_action_type_as_ref() {
        assert_eq!(ExchangeActionType::Order.as_ref(), "order");
        assert_eq!(ExchangeActionType::Cancel.as_ref(), "cancel");
        assert_eq!(ExchangeActionType::CancelByCloid.as_ref(), "cancelByCloid");
        assert_eq!(ExchangeActionType::Modify.as_ref(), "modify");
        assert_eq!(
            ExchangeActionType::UpdateLeverage.as_ref(),
            "updateLeverage"
        );
        assert_eq!(
            ExchangeActionType::UpdateIsolatedMargin.as_ref(),
            "updateIsolatedMargin"
        );
    }

    #[rstest]
    fn test_update_leverage_serialization() {
        let action = ExchangeAction::update_leverage(1, true, 10);
        let json = serde_json::to_string(&action).unwrap();

        assert!(json.contains(r#""type":"updateLeverage""#));
        assert!(json.contains(r#""asset":1"#));
        assert!(json.contains(r#""isCross":true"#));
        assert!(json.contains(r#""leverage":10"#));
    }

    #[rstest]
    fn test_update_isolated_margin_serialization() {
        let action = ExchangeAction::update_isolated_margin(2, false, 1000);
        let json = serde_json::to_string(&action).unwrap();

        assert!(json.contains(r#""type":"updateIsolatedMargin""#));
        assert!(json.contains(r#""asset":2"#));
        assert!(json.contains(r#""isBuy":false"#));
        assert!(json.contains(r#""ntli":1000"#));
    }

    #[rstest]
    fn test_cancel_by_cloid_serialization() {
        let cancel_request = HyperliquidExecCancelByCloidRequest {
            asset: 0,
            cloid: Cloid::from_hex("0x00000000000000000000000000000000").unwrap(),
        };
        let action = ExchangeAction::cancel_by_cloid(vec![cancel_request]);
        let json = serde_json::to_string(&action).unwrap();

        assert!(json.contains(r#""type":"cancelByCloid""#));
        assert!(json.contains(r#""cancels""#));
    }

    #[rstest]
    fn test_modify_serialization() {
        let modify_request = HyperliquidExecModifyOrderRequest {
            oid: 12345,
            order: HyperliquidExecPlaceOrderRequest {
                asset: 0,
                is_buy: true,
                price: Decimal::new(51000, 0),
                size: Decimal::new(2, 0),
                reduce_only: false,
                kind: HyperliquidExecOrderKind::Limit {
                    limit: HyperliquidExecLimitParams {
                        tif: HyperliquidExecTif::Gtc,
                    },
                },
                cloid: None,
            },
        };
        let action = ExchangeAction::modify(modify_request);
        let json = serde_json::to_string(&action).unwrap();

        assert!(json.contains(r#""type":"modify""#));
        assert!(json.contains(r#""oid":12345"#));
        assert!(json.contains(r#""order""#));
    }
}