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
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! Order type conversion utilities for Hyperliquid adapter.
//!
//! This module provides conversion functions between Nautilus core order types
//! and Hyperliquid-specific order type representations.

use anyhow::Context;
use nautilus_model::enums::{OrderType, TimeInForce};
use rust_decimal::Decimal;

use super::enums::{
    HyperliquidConditionalOrderType, HyperliquidOrderType, HyperliquidTimeInForce, HyperliquidTpSl,
};

/// Converts a Nautilus `OrderType` to a Hyperliquid order type configuration.
///
/// # Errors
///
/// Returns an error if the order type is unsupported, a required trigger price
/// is missing, or the time in force is not supported.
pub fn nautilus_order_type_to_hyperliquid(
    order_type: OrderType,
    time_in_force: Option<TimeInForce>,
    trigger_price: Option<Decimal>,
) -> anyhow::Result<HyperliquidOrderType> {
    let result = match order_type {
        // Regular limit order
        OrderType::Limit => {
            let tif = match time_in_force {
                Some(t) => nautilus_time_in_force_to_hyperliquid(t)?,
                None => HyperliquidTimeInForce::Gtc,
            };
            HyperliquidOrderType::Limit { tif }
        }

        // Stop market order (stop loss)
        OrderType::StopMarket => {
            let trigger_px = trigger_price
                .context("Trigger price required for StopMarket order")?
                .to_string();
            HyperliquidOrderType::Trigger {
                is_market: true,
                trigger_px,
                tpsl: HyperliquidTpSl::Sl,
            }
        }

        // Stop limit order (stop loss with limit)
        OrderType::StopLimit => {
            let trigger_px = trigger_price
                .context("Trigger price required for StopLimit order")?
                .to_string();
            HyperliquidOrderType::Trigger {
                is_market: false,
                trigger_px,
                tpsl: HyperliquidTpSl::Sl,
            }
        }

        // Market if touched (take profit market)
        OrderType::MarketIfTouched => {
            let trigger_px = trigger_price
                .context("Trigger price required for MarketIfTouched order")?
                .to_string();
            HyperliquidOrderType::Trigger {
                is_market: true,
                trigger_px,
                tpsl: HyperliquidTpSl::Tp,
            }
        }

        // Limit if touched (take profit limit)
        OrderType::LimitIfTouched => {
            let trigger_px = trigger_price
                .context("Trigger price required for LimitIfTouched order")?
                .to_string();
            HyperliquidOrderType::Trigger {
                is_market: false,
                trigger_px,
                tpsl: HyperliquidTpSl::Tp,
            }
        }

        // Trailing stop market (requires special handling)
        OrderType::TrailingStopMarket => {
            let trigger_px = trigger_price
                .context("Trigger price required for TrailingStopMarket order")?
                .to_string();
            HyperliquidOrderType::Trigger {
                is_market: true,
                trigger_px,
                tpsl: HyperliquidTpSl::Sl,
            }
        }

        // Trailing stop limit (requires special handling)
        OrderType::TrailingStopLimit => {
            let trigger_px = trigger_price
                .context("Trigger price required for TrailingStopLimit order")?
                .to_string();
            HyperliquidOrderType::Trigger {
                is_market: false,
                trigger_px,
                tpsl: HyperliquidTpSl::Sl,
            }
        }

        _ => anyhow::bail!("Unsupported order type: {order_type:?}"),
    };

    Ok(result)
}

/// Converts a Hyperliquid order type to a Nautilus `OrderType`.
pub fn hyperliquid_order_type_to_nautilus(hl_order_type: &HyperliquidOrderType) -> OrderType {
    match hl_order_type {
        HyperliquidOrderType::Limit { .. } => OrderType::Limit,
        HyperliquidOrderType::Trigger {
            is_market, tpsl, ..
        } => match (is_market, tpsl) {
            (true, HyperliquidTpSl::Sl) => OrderType::StopMarket,
            (false, HyperliquidTpSl::Sl) => OrderType::StopLimit,
            (true, HyperliquidTpSl::Tp) => OrderType::MarketIfTouched,
            (false, HyperliquidTpSl::Tp) => OrderType::LimitIfTouched,
        },
    }
}

/// Converts a Hyperliquid conditional order type to a Nautilus `OrderType`.
pub fn hyperliquid_conditional_to_nautilus(
    conditional_type: HyperliquidConditionalOrderType,
) -> OrderType {
    OrderType::from(conditional_type)
}

/// Converts a Nautilus `OrderType` to a Hyperliquid conditional order type.
///
/// # Panics
///
/// Panics if the order type is not a conditional order type.
pub fn nautilus_to_hyperliquid_conditional(
    order_type: OrderType,
) -> HyperliquidConditionalOrderType {
    HyperliquidConditionalOrderType::from(order_type)
}

/// Converts a Nautilus `TimeInForce` to a Hyperliquid time in force.
///
/// # Errors
///
/// Returns an error if the time in force is not supported (e.g. FOK).
pub fn nautilus_time_in_force_to_hyperliquid(
    tif: TimeInForce,
) -> anyhow::Result<HyperliquidTimeInForce> {
    match tif {
        TimeInForce::Gtc => Ok(HyperliquidTimeInForce::Gtc),
        TimeInForce::Ioc => Ok(HyperliquidTimeInForce::Ioc),
        TimeInForce::Fok => {
            anyhow::bail!("FOK time in force is not supported by Hyperliquid")
        }
        TimeInForce::Gtd => {
            anyhow::bail!("GTD time in force is not supported by Hyperliquid")
        }
        TimeInForce::Day => {
            anyhow::bail!("DAY time in force is not supported by Hyperliquid")
        }
        TimeInForce::AtTheOpen => {
            anyhow::bail!("AT_THE_OPEN time in force is not supported by Hyperliquid")
        }
        TimeInForce::AtTheClose => {
            anyhow::bail!("AT_THE_CLOSE time in force is not supported by Hyperliquid")
        }
    }
}

/// Converts a Hyperliquid time in force to a Nautilus `TimeInForce`.
pub fn hyperliquid_time_in_force_to_nautilus(hl_tif: HyperliquidTimeInForce) -> TimeInForce {
    match hl_tif {
        HyperliquidTimeInForce::Gtc => TimeInForce::Gtc,
        HyperliquidTimeInForce::Ioc => TimeInForce::Ioc,
        HyperliquidTimeInForce::Alo => TimeInForce::Gtc, // ALO (post-only) maps to GTC
    }
}

/// Determines the TP/SL type based on order type and side.
///
/// # Logic
///
/// For buy orders:
/// - Stop orders (trigger below current price) -> Stop Loss
/// - Take profit orders (trigger above current price) -> Take Profit
///
/// For sell orders:
/// - Stop orders (trigger above current price) -> Stop Loss
/// - Take profit orders (trigger below current price) -> Take Profit
pub fn determine_tpsl_type(order_type: OrderType, is_buy: bool) -> HyperliquidTpSl {
    match order_type {
        OrderType::StopMarket
        | OrderType::StopLimit
        | OrderType::TrailingStopMarket
        | OrderType::TrailingStopLimit => HyperliquidTpSl::Sl,
        OrderType::MarketIfTouched | OrderType::LimitIfTouched => HyperliquidTpSl::Tp,
        _ => {
            // Default logic based on side if order type is ambiguous
            if is_buy {
                HyperliquidTpSl::Sl
            } else {
                HyperliquidTpSl::Tp
            }
        }
    }
}

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

    use super::*;

    #[rstest]
    fn test_nautilus_to_hyperliquid_limit_order() {
        let result =
            nautilus_order_type_to_hyperliquid(OrderType::Limit, Some(TimeInForce::Gtc), None)
                .unwrap();

        match result {
            HyperliquidOrderType::Limit { tif } => {
                assert_eq!(tif, HyperliquidTimeInForce::Gtc);
            }
            _ => panic!("Expected Limit order type"),
        }
    }

    #[rstest]
    fn test_nautilus_to_hyperliquid_stop_market() {
        let result = nautilus_order_type_to_hyperliquid(
            OrderType::StopMarket,
            None,
            Some(Decimal::new(49000, 0)),
        )
        .unwrap();

        match result {
            HyperliquidOrderType::Trigger {
                is_market,
                trigger_px,
                tpsl,
            } => {
                assert!(is_market);
                assert_eq!(trigger_px, "49000");
                assert_eq!(tpsl, HyperliquidTpSl::Sl);
            }
            _ => panic!("Expected Trigger order type"),
        }
    }

    #[rstest]
    fn test_nautilus_to_hyperliquid_stop_limit() {
        let result = nautilus_order_type_to_hyperliquid(
            OrderType::StopLimit,
            None,
            Some(Decimal::new(49000, 0)),
        )
        .unwrap();

        match result {
            HyperliquidOrderType::Trigger {
                is_market,
                trigger_px,
                tpsl,
            } => {
                assert!(!is_market);
                assert_eq!(trigger_px, "49000");
                assert_eq!(tpsl, HyperliquidTpSl::Sl);
            }
            _ => panic!("Expected Trigger order type"),
        }
    }

    #[rstest]
    fn test_nautilus_to_hyperliquid_take_profit_market() {
        let result = nautilus_order_type_to_hyperliquid(
            OrderType::MarketIfTouched,
            None,
            Some(Decimal::new(51000, 0)),
        )
        .unwrap();

        match result {
            HyperliquidOrderType::Trigger {
                is_market,
                trigger_px,
                tpsl,
            } => {
                assert!(is_market);
                assert_eq!(trigger_px, "51000");
                assert_eq!(tpsl, HyperliquidTpSl::Tp);
            }
            _ => panic!("Expected Trigger order type"),
        }
    }

    #[rstest]
    fn test_nautilus_to_hyperliquid_take_profit_limit() {
        let result = nautilus_order_type_to_hyperliquid(
            OrderType::LimitIfTouched,
            None,
            Some(Decimal::new(51000, 0)),
        )
        .unwrap();

        match result {
            HyperliquidOrderType::Trigger {
                is_market,
                trigger_px,
                tpsl,
            } => {
                assert!(!is_market);
                assert_eq!(trigger_px, "51000");
                assert_eq!(tpsl, HyperliquidTpSl::Tp);
            }
            _ => panic!("Expected Trigger order type"),
        }
    }

    #[rstest]
    fn test_hyperliquid_to_nautilus_limit() {
        let hl_order = HyperliquidOrderType::Limit {
            tif: HyperliquidTimeInForce::Gtc,
        };
        assert_eq!(
            hyperliquid_order_type_to_nautilus(&hl_order),
            OrderType::Limit
        );
    }

    #[rstest]
    fn test_hyperliquid_to_nautilus_stop_market() {
        let hl_order = HyperliquidOrderType::Trigger {
            is_market: true,
            trigger_px: "49000".to_string(),
            tpsl: HyperliquidTpSl::Sl,
        };
        assert_eq!(
            hyperliquid_order_type_to_nautilus(&hl_order),
            OrderType::StopMarket
        );
    }

    #[rstest]
    fn test_hyperliquid_to_nautilus_stop_limit() {
        let hl_order = HyperliquidOrderType::Trigger {
            is_market: false,
            trigger_px: "49000".to_string(),
            tpsl: HyperliquidTpSl::Sl,
        };
        assert_eq!(
            hyperliquid_order_type_to_nautilus(&hl_order),
            OrderType::StopLimit
        );
    }

    #[rstest]
    fn test_hyperliquid_to_nautilus_take_profit_market() {
        let hl_order = HyperliquidOrderType::Trigger {
            is_market: true,
            trigger_px: "51000".to_string(),
            tpsl: HyperliquidTpSl::Tp,
        };
        assert_eq!(
            hyperliquid_order_type_to_nautilus(&hl_order),
            OrderType::MarketIfTouched
        );
    }

    #[rstest]
    fn test_hyperliquid_to_nautilus_take_profit_limit() {
        let hl_order = HyperliquidOrderType::Trigger {
            is_market: false,
            trigger_px: "51000".to_string(),
            tpsl: HyperliquidTpSl::Tp,
        };
        assert_eq!(
            hyperliquid_order_type_to_nautilus(&hl_order),
            OrderType::LimitIfTouched
        );
    }

    #[rstest]
    fn test_time_in_force_conversions() {
        // Test Nautilus to Hyperliquid
        assert_eq!(
            nautilus_time_in_force_to_hyperliquid(TimeInForce::Gtc).unwrap(),
            HyperliquidTimeInForce::Gtc
        );
        assert_eq!(
            nautilus_time_in_force_to_hyperliquid(TimeInForce::Ioc).unwrap(),
            HyperliquidTimeInForce::Ioc
        );

        // Test Hyperliquid to Nautilus
        assert_eq!(
            hyperliquid_time_in_force_to_nautilus(HyperliquidTimeInForce::Gtc),
            TimeInForce::Gtc
        );
        assert_eq!(
            hyperliquid_time_in_force_to_nautilus(HyperliquidTimeInForce::Ioc),
            TimeInForce::Ioc
        );
        assert_eq!(
            hyperliquid_time_in_force_to_nautilus(HyperliquidTimeInForce::Alo),
            TimeInForce::Gtc
        );
    }

    #[rstest]
    #[case(TimeInForce::Fok, "FOK")]
    #[case(TimeInForce::Gtd, "GTD")]
    #[case(TimeInForce::Day, "DAY")]
    #[case(TimeInForce::AtTheOpen, "AT_THE_OPEN")]
    #[case(TimeInForce::AtTheClose, "AT_THE_CLOSE")]
    fn test_unsupported_time_in_force_returns_error(#[case] tif: TimeInForce, #[case] name: &str) {
        let result = nautilus_time_in_force_to_hyperliquid(tif);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains(&format!("{name} time in force is not supported"))
        );
    }

    #[rstest]
    fn test_conditional_order_type_conversions() {
        // Test Hyperliquid conditional to Nautilus
        assert_eq!(
            hyperliquid_conditional_to_nautilus(HyperliquidConditionalOrderType::StopMarket),
            OrderType::StopMarket
        );
        assert_eq!(
            hyperliquid_conditional_to_nautilus(HyperliquidConditionalOrderType::StopLimit),
            OrderType::StopLimit
        );
        assert_eq!(
            hyperliquid_conditional_to_nautilus(HyperliquidConditionalOrderType::TakeProfitMarket),
            OrderType::MarketIfTouched
        );
        assert_eq!(
            hyperliquid_conditional_to_nautilus(HyperliquidConditionalOrderType::TakeProfitLimit),
            OrderType::LimitIfTouched
        );

        // Test Nautilus to Hyperliquid conditional
        assert_eq!(
            nautilus_to_hyperliquid_conditional(OrderType::StopMarket),
            HyperliquidConditionalOrderType::StopMarket
        );
        assert_eq!(
            nautilus_to_hyperliquid_conditional(OrderType::StopLimit),
            HyperliquidConditionalOrderType::StopLimit
        );
        assert_eq!(
            nautilus_to_hyperliquid_conditional(OrderType::MarketIfTouched),
            HyperliquidConditionalOrderType::TakeProfitMarket
        );
        assert_eq!(
            nautilus_to_hyperliquid_conditional(OrderType::LimitIfTouched),
            HyperliquidConditionalOrderType::TakeProfitLimit
        );
    }

    #[rstest]
    fn test_determine_tpsl_type() {
        // Stop orders should always be SL
        assert_eq!(
            determine_tpsl_type(OrderType::StopMarket, true),
            HyperliquidTpSl::Sl
        );
        assert_eq!(
            determine_tpsl_type(OrderType::StopLimit, false),
            HyperliquidTpSl::Sl
        );

        // Take profit orders should always be TP
        assert_eq!(
            determine_tpsl_type(OrderType::MarketIfTouched, true),
            HyperliquidTpSl::Tp
        );
        assert_eq!(
            determine_tpsl_type(OrderType::LimitIfTouched, false),
            HyperliquidTpSl::Tp
        );

        // Trailing stops should be SL
        assert_eq!(
            determine_tpsl_type(OrderType::TrailingStopMarket, true),
            HyperliquidTpSl::Sl
        );
        assert_eq!(
            determine_tpsl_type(OrderType::TrailingStopLimit, false),
            HyperliquidTpSl::Sl
        );
    }
}