1use serde::{Serialize, ser::SerializeStruct};
17
18use crate::{
19 common::{
20 enums::{HyperliquidBarInterval, HyperliquidInfoRequestType},
21 parse::is_false_or_none,
22 },
23 http::models::{
24 Cloid, HyperliquidExchangeBuilderFee, HyperliquidExchangeCancelByCloidRequest,
25 HyperliquidExchangeGrouping, HyperliquidExchangeModifyOrderRequest,
26 HyperliquidExchangePlaceOrderRequest,
27 },
28};
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
32#[serde(rename_all = "camelCase")]
33pub enum ExchangeActionType {
34 Order,
36 Cancel,
38 CancelByCloid,
40 Modify,
42 UpdateLeverage,
44 UpdateIsolatedMargin,
46}
47
48impl AsRef<str> for ExchangeActionType {
49 fn as_ref(&self) -> &str {
50 match self {
51 Self::Order => "order",
52 Self::Cancel => "cancel",
53 Self::CancelByCloid => "cancelByCloid",
54 Self::Modify => "modify",
55 Self::UpdateLeverage => "updateLeverage",
56 Self::UpdateIsolatedMargin => "updateIsolatedMargin",
57 }
58 }
59}
60
61#[derive(Debug, Clone, Serialize)]
63pub struct OrderParams {
64 pub orders: Vec<HyperliquidExchangePlaceOrderRequest>,
65 pub grouping: HyperliquidExchangeGrouping,
66 #[serde(skip_serializing_if = "Option::is_none")]
67 pub builder: Option<HyperliquidExchangeBuilderFee>,
68}
69
70#[derive(Debug, Clone, Serialize)]
74pub struct CancelParams {
75 pub cancels: Vec<HyperliquidExchangeCancelByCloidRequest>,
76 #[serde(rename = "f", skip_serializing_if = "is_false_or_none")]
77 pub fast: Option<bool>,
78}
79
80#[derive(Debug, Clone, Serialize)]
82pub struct ModifyParams {
83 #[serde(flatten)]
84 pub request: HyperliquidExchangeModifyOrderRequest,
85}
86
87#[derive(Debug, Clone, Serialize)]
89#[serde(rename_all = "camelCase")]
90pub struct UpdateLeverageParams {
91 pub asset: u32,
92 pub is_cross: bool,
93 pub leverage: u32,
94}
95
96#[derive(Debug, Clone, Serialize)]
98#[serde(rename_all = "camelCase")]
99pub struct UpdateIsolatedMarginParams {
100 pub asset: u32,
101 pub is_buy: bool,
102 pub ntli: i64,
103}
104
105#[derive(Debug, Clone, Serialize)]
107pub struct L2BookParams {
108 pub coin: String,
109}
110
111#[derive(Debug, Clone, Serialize)]
113pub struct RecentTradesParams {
114 pub coin: String,
115}
116
117#[derive(Debug, Clone)]
119pub struct UserFillsParams {
120 pub user: String,
121}
122
123impl Serialize for UserFillsParams {
124 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
125 where
126 S: serde::Serializer,
127 {
128 let mut state = serializer.serialize_struct("UserFillsParams", 2)?;
129 state.serialize_field("user", &self.user)?;
130 state.serialize_field("aggregateByTime", &false)?;
131 state.end()
132 }
133}
134
135#[derive(Debug, Clone, Serialize)]
137pub struct OrderStatusParams {
138 pub user: String,
139 pub oid: u64,
140}
141
142#[derive(Debug, Clone, Serialize)]
146pub struct OrderStatusByCloidParams {
147 pub user: String,
148 #[serde(rename = "oid")]
149 pub cloid: Cloid,
150}
151
152#[derive(Debug, Clone, Serialize)]
154pub struct OpenOrdersParams {
155 pub user: String,
156 #[serde(skip_serializing_if = "Option::is_none")]
157 pub dex: Option<String>,
158}
159
160#[derive(Debug, Clone, Serialize)]
162pub struct ClearinghouseStateParams {
163 pub user: String,
164 #[serde(skip_serializing_if = "Option::is_none")]
165 pub dex: Option<String>,
166}
167
168#[derive(Debug, Clone, Serialize)]
170pub struct SpotClearinghouseStateParams {
171 pub user: String,
172}
173
174#[derive(Debug, Clone, Serialize)]
176#[serde(rename_all = "camelCase")]
177pub struct CandleSnapshotReq {
178 pub coin: String,
179 pub interval: HyperliquidBarInterval,
180 pub start_time: u64,
181 pub end_time: u64,
182}
183
184#[derive(Debug, Clone, Serialize)]
186pub struct CandleSnapshotParams {
187 pub req: CandleSnapshotReq,
188}
189
190#[derive(Debug, Clone, Serialize)]
192#[serde(rename_all = "camelCase")]
193pub struct FundingHistoryParams {
194 pub coin: String,
195 pub start_time: u64,
196 #[serde(skip_serializing_if = "Option::is_none")]
197 pub end_time: Option<u64>,
198}
199
200#[derive(Debug, Clone, Serialize)]
202#[serde(untagged)]
203pub enum InfoRequestParams {
204 L2Book(L2BookParams),
205 RecentTrades(RecentTradesParams),
206 UserFills(UserFillsParams),
207 OrderStatus(OrderStatusParams),
208 OrderStatusByCloid(OrderStatusByCloidParams),
209 OpenOrders(OpenOrdersParams),
210 ClearinghouseState(ClearinghouseStateParams),
211 SpotClearinghouseState(SpotClearinghouseStateParams),
212 CandleSnapshot(CandleSnapshotParams),
213 FundingHistory(FundingHistoryParams),
214 None,
215}
216
217#[derive(Debug, Clone, Serialize)]
219pub struct InfoRequest {
220 #[serde(rename = "type")]
221 pub request_type: HyperliquidInfoRequestType,
222 #[serde(flatten)]
223 pub params: InfoRequestParams,
224}
225
226impl InfoRequest {
227 pub fn meta() -> Self {
229 Self {
230 request_type: HyperliquidInfoRequestType::Meta,
231 params: InfoRequestParams::None,
232 }
233 }
234
235 pub fn all_perp_metas() -> Self {
237 Self {
238 request_type: HyperliquidInfoRequestType::AllPerpMetas,
239 params: InfoRequestParams::None,
240 }
241 }
242
243 pub fn perp_dexs() -> Self {
245 Self {
246 request_type: HyperliquidInfoRequestType::PerpDexs,
247 params: InfoRequestParams::None,
248 }
249 }
250
251 pub fn spot_meta() -> Self {
253 Self {
254 request_type: HyperliquidInfoRequestType::SpotMeta,
255 params: InfoRequestParams::None,
256 }
257 }
258
259 pub fn meta_and_asset_ctxs() -> Self {
261 Self {
262 request_type: HyperliquidInfoRequestType::MetaAndAssetCtxs,
263 params: InfoRequestParams::None,
264 }
265 }
266
267 pub fn spot_meta_and_asset_ctxs() -> Self {
269 Self {
270 request_type: HyperliquidInfoRequestType::SpotMetaAndAssetCtxs,
271 params: InfoRequestParams::None,
272 }
273 }
274
275 pub fn outcome_meta() -> Self {
277 Self {
278 request_type: HyperliquidInfoRequestType::OutcomeMeta,
279 params: InfoRequestParams::None,
280 }
281 }
282
283 pub fn l2_book(coin: &str) -> Self {
285 Self {
286 request_type: HyperliquidInfoRequestType::L2Book,
287 params: InfoRequestParams::L2Book(L2BookParams {
288 coin: coin.to_string(),
289 }),
290 }
291 }
292
293 pub fn recent_trades(coin: &str) -> Self {
295 Self {
296 request_type: HyperliquidInfoRequestType::RecentTrades,
297 params: InfoRequestParams::RecentTrades(RecentTradesParams {
298 coin: coin.to_string(),
299 }),
300 }
301 }
302
303 pub fn user_fills(user: &str) -> Self {
305 Self {
306 request_type: HyperliquidInfoRequestType::UserFills,
307 params: InfoRequestParams::UserFills(UserFillsParams {
308 user: user.to_string(),
309 }),
310 }
311 }
312
313 pub fn order_status(user: &str, oid: u64) -> Self {
315 Self {
316 request_type: HyperliquidInfoRequestType::OrderStatus,
317 params: InfoRequestParams::OrderStatus(OrderStatusParams {
318 user: user.to_string(),
319 oid,
320 }),
321 }
322 }
323
324 pub(crate) fn order_status_by_cloid(user: &str, cloid: Cloid) -> Self {
326 Self {
327 request_type: HyperliquidInfoRequestType::OrderStatus,
328 params: InfoRequestParams::OrderStatusByCloid(OrderStatusByCloidParams {
329 user: user.to_string(),
330 cloid,
331 }),
332 }
333 }
334
335 pub fn open_orders(user: &str) -> Self {
337 Self::open_orders_for_dex(user, None)
338 }
339
340 pub(crate) fn open_orders_for_dex(user: &str, dex: Option<&str>) -> Self {
342 Self {
343 request_type: HyperliquidInfoRequestType::OpenOrders,
344 params: InfoRequestParams::OpenOrders(OpenOrdersParams {
345 user: user.to_string(),
346 dex: dex.map(str::to_string),
347 }),
348 }
349 }
350
351 pub fn frontend_open_orders(user: &str) -> Self {
353 Self::frontend_open_orders_for_dex(user, None)
354 }
355
356 pub(crate) fn frontend_open_orders_for_dex(user: &str, dex: Option<&str>) -> Self {
358 Self {
359 request_type: HyperliquidInfoRequestType::FrontendOpenOrders,
360 params: InfoRequestParams::OpenOrders(OpenOrdersParams {
361 user: user.to_string(),
362 dex: dex.map(str::to_string),
363 }),
364 }
365 }
366
367 pub fn historical_orders(user: &str) -> Self {
369 Self {
370 request_type: HyperliquidInfoRequestType::HistoricalOrders,
371 params: InfoRequestParams::OpenOrders(OpenOrdersParams {
372 user: user.to_string(),
373 dex: None,
374 }),
375 }
376 }
377
378 pub fn clearinghouse_state(user: &str) -> Self {
380 Self::clearinghouse_state_for_dex(user, None)
381 }
382
383 pub(crate) fn clearinghouse_state_for_dex(user: &str, dex: Option<&str>) -> Self {
385 Self {
386 request_type: HyperliquidInfoRequestType::ClearinghouseState,
387 params: InfoRequestParams::ClearinghouseState(ClearinghouseStateParams {
388 user: user.to_string(),
389 dex: dex.map(str::to_string),
390 }),
391 }
392 }
393
394 pub fn spot_clearinghouse_state(user: &str) -> Self {
396 Self {
397 request_type: HyperliquidInfoRequestType::SpotClearinghouseState,
398 params: InfoRequestParams::SpotClearinghouseState(SpotClearinghouseStateParams {
399 user: user.to_string(),
400 }),
401 }
402 }
403
404 pub fn user_abstraction(user: &str) -> Self {
406 Self {
407 request_type: HyperliquidInfoRequestType::UserAbstraction,
408 params: InfoRequestParams::SpotClearinghouseState(SpotClearinghouseStateParams {
409 user: user.to_string(),
410 }),
411 }
412 }
413
414 pub fn user_fees(user: &str) -> Self {
416 Self {
417 request_type: HyperliquidInfoRequestType::UserFees,
418 params: InfoRequestParams::OpenOrders(OpenOrdersParams {
419 user: user.to_string(),
420 dex: None,
421 }),
422 }
423 }
424
425 pub fn candle_snapshot(
427 coin: &str,
428 interval: HyperliquidBarInterval,
429 start_time: u64,
430 end_time: u64,
431 ) -> Self {
432 Self {
433 request_type: HyperliquidInfoRequestType::CandleSnapshot,
434 params: InfoRequestParams::CandleSnapshot(CandleSnapshotParams {
435 req: CandleSnapshotReq {
436 coin: coin.to_string(),
437 interval,
438 start_time,
439 end_time,
440 },
441 }),
442 }
443 }
444
445 pub fn funding_history(coin: &str, start_time: u64, end_time: Option<u64>) -> Self {
447 Self {
448 request_type: HyperliquidInfoRequestType::FundingHistory,
449 params: InfoRequestParams::FundingHistory(FundingHistoryParams {
450 coin: coin.to_string(),
451 start_time,
452 end_time,
453 }),
454 }
455 }
456}
457
458#[derive(Debug, Clone, Serialize)]
460#[serde(untagged)]
461pub enum ExchangeActionParams {
462 Order(OrderParams),
463 Cancel(CancelParams),
464 Modify(ModifyParams),
465 UpdateLeverage(UpdateLeverageParams),
466 UpdateIsolatedMargin(UpdateIsolatedMarginParams),
467}
468
469#[derive(Debug, Clone, Serialize)]
471pub struct ExchangeAction {
472 #[serde(rename = "type", serialize_with = "serialize_action_type")]
473 pub action_type: ExchangeActionType,
474 #[serde(flatten)]
475 pub params: ExchangeActionParams,
476}
477
478fn serialize_action_type<S>(
479 action_type: &ExchangeActionType,
480 serializer: S,
481) -> Result<S::Ok, S::Error>
482where
483 S: serde::Serializer,
484{
485 serializer.serialize_str(action_type.as_ref())
486}
487
488impl ExchangeAction {
489 pub fn order(
491 orders: Vec<HyperliquidExchangePlaceOrderRequest>,
492 builder: Option<HyperliquidExchangeBuilderFee>,
493 ) -> Self {
494 Self {
495 action_type: ExchangeActionType::Order,
496 params: ExchangeActionParams::Order(OrderParams {
497 orders,
498 grouping: HyperliquidExchangeGrouping::Na,
499 builder,
500 }),
501 }
502 }
503
504 pub fn cancel(cancels: Vec<HyperliquidExchangeCancelByCloidRequest>) -> Self {
506 Self {
507 action_type: ExchangeActionType::Cancel,
508 params: ExchangeActionParams::Cancel(CancelParams {
509 cancels,
510 fast: None,
511 }),
512 }
513 }
514
515 pub fn cancel_by_cloid(cancels: Vec<HyperliquidExchangeCancelByCloidRequest>) -> Self {
517 Self {
518 action_type: ExchangeActionType::CancelByCloid,
519 params: ExchangeActionParams::Cancel(CancelParams {
520 cancels,
521 fast: None,
522 }),
523 }
524 }
525
526 pub fn modify(request: HyperliquidExchangeModifyOrderRequest) -> Self {
528 Self {
529 action_type: ExchangeActionType::Modify,
530 params: ExchangeActionParams::Modify(ModifyParams { request }),
531 }
532 }
533
534 pub fn update_leverage(asset: u32, is_cross: bool, leverage: u32) -> Self {
536 Self {
537 action_type: ExchangeActionType::UpdateLeverage,
538 params: ExchangeActionParams::UpdateLeverage(UpdateLeverageParams {
539 asset,
540 is_cross,
541 leverage,
542 }),
543 }
544 }
545
546 pub fn update_isolated_margin(asset: u32, is_buy: bool, ntli: i64) -> Self {
548 Self {
549 action_type: ExchangeActionType::UpdateIsolatedMargin,
550 params: ExchangeActionParams::UpdateIsolatedMargin(UpdateIsolatedMarginParams {
551 asset,
552 is_buy,
553 ntli,
554 }),
555 }
556 }
557}
558
559#[cfg(test)]
560mod tests {
561 use rstest::rstest;
562 use rust_decimal::Decimal;
563
564 use super::*;
565 use crate::http::models::{
566 Cloid, HyperliquidExchangeCancelByCloidRequest, HyperliquidExchangeLimitParams,
567 HyperliquidExchangeModifyOrderRequest, HyperliquidExchangeOrderKind,
568 HyperliquidExchangePlaceOrderRequest, HyperliquidExchangeTif,
569 };
570
571 #[rstest]
572 fn test_cancel_action_serialization(
573 #[values(None, Some(false), Some(true))] fast: Option<bool>,
574 #[values(false, true)] by_cloid: bool,
575 ) {
576 let cancels = vec![HyperliquidExchangeCancelByCloidRequest {
577 asset: 7,
578 cloid: Cloid::from_hex("0x0123456789abcdef0123456789abcdef").unwrap(),
579 }];
580
581 let (mut action, name) = if by_cloid {
582 (ExchangeAction::cancel_by_cloid(cancels), "cancel_by_cloid")
583 } else {
584 (ExchangeAction::cancel(cancels), "query_cancel")
585 };
586
587 let ExchangeActionParams::Cancel(params) = &mut action.params else {
588 panic!("Expected cancel parameters");
589 };
590
591 params.fast = fast;
592 let fixtures: serde_json::Value =
593 serde_json::from_str(include_str!("../../test_data/cancel_actions.json")).unwrap();
594 let expected = &fixtures[name][if fast == Some(true) { "fast" } else { "normal" }];
595 let json = serde_json::to_value(&action).unwrap();
596 let msgpack = rmp_serde::to_vec_named(&action).unwrap();
597
598 assert_eq!(json, expected["json"]);
599 assert_eq!(
600 nautilus_core::hex::encode(msgpack),
601 expected["msgpack"].as_str().unwrap()
602 );
603 }
604
605 #[rstest]
606 fn test_info_request_meta() {
607 let req = InfoRequest::meta();
608
609 assert_eq!(req.request_type, HyperliquidInfoRequestType::Meta);
610 assert!(matches!(req.params, InfoRequestParams::None));
611 }
612
613 #[rstest]
614 fn test_info_request_all_perp_metas() {
615 let req = InfoRequest::all_perp_metas();
616
617 assert_eq!(req.request_type, HyperliquidInfoRequestType::AllPerpMetas);
618 let json = serde_json::to_string(&req).unwrap();
619 assert!(json.contains(r#""type":"allPerpMetas""#));
620 }
621
622 #[rstest]
623 fn test_info_request_outcome_meta() {
624 let req = InfoRequest::outcome_meta();
625
626 assert_eq!(req.request_type, HyperliquidInfoRequestType::OutcomeMeta);
627 assert!(matches!(req.params, InfoRequestParams::None));
628 let json = serde_json::to_string(&req).unwrap();
629 assert_eq!(json, r#"{"type":"outcomeMeta"}"#);
630 }
631
632 #[rstest]
633 fn test_info_request_l2_book() {
634 let req = InfoRequest::l2_book("BTC");
635
636 assert_eq!(req.request_type, HyperliquidInfoRequestType::L2Book);
637 let json = serde_json::to_string(&req).unwrap();
638 assert!(json.contains("\"coin\":\"BTC\""));
639 }
640
641 #[rstest]
642 fn test_info_request_recent_trades() {
643 let req = InfoRequest::recent_trades("BTC");
644
645 assert_eq!(req.request_type, HyperliquidInfoRequestType::RecentTrades);
646 let json = serde_json::to_string(&req).unwrap();
647 assert_eq!(json, r#"{"type":"recentTrades","coin":"BTC"}"#);
648 }
649
650 #[rstest]
651 fn test_info_request_order_status_serialization() {
652 let cloid = Cloid::from_hex("0x00000000000000000000000000000abc").unwrap();
653 let by_oid = serde_json::to_value(InfoRequest::order_status("0xabc", 42)).unwrap();
654 let by_cloid =
655 serde_json::to_value(InfoRequest::order_status_by_cloid("0xabc", cloid)).unwrap();
656
657 assert_eq!(
658 by_oid,
659 serde_json::json!({"type": "orderStatus", "user": "0xabc", "oid": 42})
660 );
661 assert_eq!(
662 by_cloid,
663 serde_json::json!({
664 "type": "orderStatus",
665 "user": "0xabc",
666 "oid": "0x00000000000000000000000000000abc",
667 })
668 );
669 }
670
671 #[rstest]
672 fn test_info_request_open_orders_dex_serialization() {
673 let default = serde_json::to_value(InfoRequest::open_orders("0xabc")).unwrap();
674 let xyz =
675 serde_json::to_value(InfoRequest::open_orders_for_dex("0xabc", Some("xyz"))).unwrap();
676
677 assert_eq!(
678 default,
679 serde_json::json!({"type": "openOrders", "user": "0xabc"})
680 );
681 assert_eq!(
682 xyz,
683 serde_json::json!({"type": "openOrders", "user": "0xabc", "dex": "xyz"})
684 );
685 }
686
687 #[rstest]
688 fn test_info_request_frontend_open_orders_dex_serialization() {
689 let default = serde_json::to_value(InfoRequest::frontend_open_orders("0xabc")).unwrap();
690 let xyz = serde_json::to_value(InfoRequest::frontend_open_orders_for_dex(
691 "0xabc",
692 Some("xyz"),
693 ))
694 .unwrap();
695
696 assert_eq!(
697 default,
698 serde_json::json!({"type": "frontendOpenOrders", "user": "0xabc"})
699 );
700 assert_eq!(
701 xyz,
702 serde_json::json!({"type": "frontendOpenOrders", "user": "0xabc", "dex": "xyz"})
703 );
704 }
705
706 #[rstest]
707 fn test_info_request_clearinghouse_state_dex_serialization() {
708 let default = serde_json::to_value(InfoRequest::clearinghouse_state("0xabc")).unwrap();
709 let xyz = serde_json::to_value(InfoRequest::clearinghouse_state_for_dex(
710 "0xabc",
711 Some("xyz"),
712 ))
713 .unwrap();
714
715 assert_eq!(
716 default,
717 serde_json::json!({"type": "clearinghouseState", "user": "0xabc"})
718 );
719 assert_eq!(
720 xyz,
721 serde_json::json!({"type": "clearinghouseState", "user": "0xabc", "dex": "xyz"})
722 );
723 }
724
725 #[rstest]
726 fn test_info_request_spot_clearinghouse_state() {
727 let req = InfoRequest::spot_clearinghouse_state("0xabc");
728
729 assert_eq!(
730 req.request_type,
731 HyperliquidInfoRequestType::SpotClearinghouseState
732 );
733 let json = serde_json::to_string(&req).unwrap();
734 assert!(json.contains(r#""type":"spotClearinghouseState""#));
735 assert!(json.contains(r#""user":"0xabc""#));
736 }
737
738 #[rstest]
739 fn test_info_request_user_abstraction() {
740 let req = InfoRequest::user_abstraction("0xabc");
741
742 assert_eq!(
743 serde_json::to_value(&req).unwrap(),
744 serde_json::json!({"type": "userAbstraction", "user": "0xabc"})
745 );
746 }
747
748 #[rstest]
749 fn test_info_request_funding_history_with_end_time() {
750 let req = InfoRequest::funding_history("BTC", 1_700_000_000_000, Some(1_700_003_600_000));
751
752 assert_eq!(req.request_type, HyperliquidInfoRequestType::FundingHistory);
753 let json = serde_json::to_string(&req).unwrap();
754 assert!(json.contains(r#""type":"fundingHistory""#));
755 assert!(json.contains(r#""coin":"BTC""#));
756 assert!(json.contains(r#""startTime":1700000000000"#));
757 assert!(json.contains(r#""endTime":1700003600000"#));
758 }
759
760 #[rstest]
761 fn test_info_request_funding_history_omits_end_time_when_none() {
762 let req = InfoRequest::funding_history("BTC", 1_700_000_000_000, None);
765 let json = serde_json::to_string(&req).unwrap();
766 assert!(json.contains(r#""startTime":1700000000000"#));
767 assert!(
768 !json.contains("endTime"),
769 "endTime must be omitted when None; json={json}",
770 );
771 }
772
773 #[rstest]
774 fn test_exchange_action_order() {
775 let order = HyperliquidExchangePlaceOrderRequest {
776 asset: 0,
777 is_buy: true,
778 price: Decimal::new(50000, 0),
779 size: Decimal::new(1, 0),
780 reduce_only: false,
781 kind: HyperliquidExchangeOrderKind::Limit {
782 limit: HyperliquidExchangeLimitParams {
783 tif: HyperliquidExchangeTif::Gtc,
784 },
785 },
786 cloid: None,
787 };
788
789 let action = ExchangeAction::order(vec![order], None);
790
791 assert_eq!(action.action_type, ExchangeActionType::Order);
792 let json = serde_json::to_string(&action).unwrap();
793 assert!(json.contains("\"orders\""));
794 }
795
796 #[rstest]
797 fn test_exchange_action_cancel() {
798 let cancel = HyperliquidExchangeCancelByCloidRequest {
799 asset: 0,
800 cloid: Cloid::from_hex("0x00000000000000000000000000000000").unwrap(),
801 };
802
803 let action = ExchangeAction::cancel(vec![cancel]);
804
805 assert_eq!(action.action_type, ExchangeActionType::Cancel);
806 }
807
808 #[rstest]
809 fn test_exchange_action_serialization() {
810 let order = HyperliquidExchangePlaceOrderRequest {
811 asset: 0,
812 is_buy: true,
813 price: Decimal::new(50000, 0),
814 size: Decimal::new(1, 0),
815 reduce_only: false,
816 kind: HyperliquidExchangeOrderKind::Limit {
817 limit: HyperliquidExchangeLimitParams {
818 tif: HyperliquidExchangeTif::Gtc,
819 },
820 },
821 cloid: None,
822 };
823
824 let action = ExchangeAction::order(vec![order], None);
825
826 let json = serde_json::to_string(&action).unwrap();
827 assert!(json.contains(r#""type":"order""#));
829 assert!(json.contains(r#""orders""#));
830 assert!(json.contains(r#""grouping":"na""#));
831 }
832
833 #[rstest]
834 fn test_exchange_action_type_as_ref() {
835 assert_eq!(ExchangeActionType::Order.as_ref(), "order");
836 assert_eq!(ExchangeActionType::Cancel.as_ref(), "cancel");
837 assert_eq!(ExchangeActionType::CancelByCloid.as_ref(), "cancelByCloid");
838 assert_eq!(ExchangeActionType::Modify.as_ref(), "modify");
839 assert_eq!(
840 ExchangeActionType::UpdateLeverage.as_ref(),
841 "updateLeverage"
842 );
843 assert_eq!(
844 ExchangeActionType::UpdateIsolatedMargin.as_ref(),
845 "updateIsolatedMargin"
846 );
847 }
848
849 #[rstest]
850 fn test_update_leverage_serialization() {
851 let action = ExchangeAction::update_leverage(1, true, 10);
852 let json = serde_json::to_string(&action).unwrap();
853
854 assert!(json.contains(r#""type":"updateLeverage""#));
855 assert!(json.contains(r#""asset":1"#));
856 assert!(json.contains(r#""isCross":true"#));
857 assert!(json.contains(r#""leverage":10"#));
858 }
859
860 #[rstest]
861 fn test_update_isolated_margin_serialization() {
862 let action = ExchangeAction::update_isolated_margin(2, false, 1000);
863 let json = serde_json::to_string(&action).unwrap();
864
865 assert!(json.contains(r#""type":"updateIsolatedMargin""#));
866 assert!(json.contains(r#""asset":2"#));
867 assert!(json.contains(r#""isBuy":false"#));
868 assert!(json.contains(r#""ntli":1000"#));
869 }
870
871 #[rstest]
872 fn test_cancel_by_cloid_serialization() {
873 let cancel_request = HyperliquidExchangeCancelByCloidRequest {
874 asset: 0,
875 cloid: Cloid::from_hex("0x00000000000000000000000000000000").unwrap(),
876 };
877 let action = ExchangeAction::cancel_by_cloid(vec![cancel_request]);
878 let json = serde_json::to_string(&action).unwrap();
879
880 assert!(json.contains(r#""type":"cancelByCloid""#));
881 assert!(json.contains(r#""cancels""#));
882 }
883
884 #[rstest]
885 fn test_modify_serialization() {
886 let modify_request = HyperliquidExchangeModifyOrderRequest {
887 oid: 12345.into(),
888 order: HyperliquidExchangePlaceOrderRequest {
889 asset: 0,
890 is_buy: true,
891 price: Decimal::new(51000, 0),
892 size: Decimal::new(2, 0),
893 reduce_only: false,
894 kind: HyperliquidExchangeOrderKind::Limit {
895 limit: HyperliquidExchangeLimitParams {
896 tif: HyperliquidExchangeTif::Gtc,
897 },
898 },
899 cloid: None,
900 },
901 };
902 let action = ExchangeAction::modify(modify_request);
903 let json = serde_json::to_string(&action).unwrap();
904
905 assert!(json.contains(r#""type":"modify""#));
906 assert!(json.contains(r#""oid":12345"#));
907 assert!(json.contains(r#""order""#));
908 }
909}