lighter-sdk 0.1.1

Rust SDK for interacting with the Lighter exchange over REST, WebSocket, and signer-backed transaction flows.
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use futures_util::{SinkExt, StreamExt};
use tokio::sync::Mutex;
use tokio::time::{self, MissedTickBehavior};
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::{Bytes, Message};
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};

use crate::config::Config;
use crate::error::{Result, SdkError};
use crate::models::market::PerpsMarketStats;
use crate::models::order::Order;
use crate::models::ws::{
    WsAccountAllAssetsUpdate, WsAccountAllOrdersUpdate, WsAccountAllPositionsUpdate,
    WsAccountAllTradesUpdate, WsAccountAllUpdate, WsAccountOrdersUpdate,
    WsAccountSpotAvgEntryPricesUpdate, WsMarketStatsUpdate, WsOrderBookMessage, WsOrderBookState,
    WsTickerUpdate, WsUserStatsUpdate,
};

use super::handler::{
    AccountAllAssetsHandler, AccountAllPositionsHandler, AccountAllTradesHandler, AccountHandler,
    AccountOrdersHandler, AccountSpotAvgEntryPricesHandler, MarketStatsHandler, OrderBookHandler,
    UserStatsHandler,
};

type OrderBookCallback = Box<dyn Fn(i64, &WsOrderBookState) + Send + Sync>;
type TickerCallback = Box<dyn Fn(i64, Option<f64>, Option<f64>) + Send + Sync>;
type AccountCallback = Box<dyn Fn(i64, &WsAccountAllUpdate) + Send + Sync>;
type AccountOrdersCallback = Box<dyn Fn(i64, &[Order]) + Send + Sync>;
type AccountAllOrdersCallback = Box<dyn Fn(i64, &HashMap<String, Vec<Order>>) + Send + Sync>;
type AccountAllPositionsCallback = Box<dyn Fn(i64, &WsAccountAllPositionsUpdate) + Send + Sync>;
type AccountAllAssetsCallback = Box<dyn Fn(i64, &WsAccountAllAssetsUpdate) + Send + Sync>;
type AccountSpotAvgEntryPricesCallback =
    Box<dyn Fn(i64, &WsAccountSpotAvgEntryPricesUpdate) + Send + Sync>;
type AccountAllTradesCallback = Box<dyn Fn(i64, &WsAccountAllTradesUpdate) + Send + Sync>;
type UserStatsCallback = Box<dyn Fn(i64, &WsUserStatsUpdate) + Send + Sync>;
type MarketStatsCallback = Box<dyn Fn(i64, &WsMarketStatsUpdate) + Send + Sync>;
type WsWriteSink = futures_util::stream::SplitSink<
    WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>,
    Message,
>;

const WS_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(20);

struct AccountOrdersSubscription {
    market_id: i64,
    account_id: i64,
}

pub struct WsClient {
    ws_url: String,
    auth_token: Option<String>,
    order_book_ids: Vec<i64>,
    ticker_ids: Vec<i64>,
    market_stats_ids: Vec<i64>,
    account_ids: Vec<i64>,
    account_all_positions_ids: Vec<i64>,
    account_all_assets_ids: Vec<i64>,
    account_spot_avg_entry_prices_ids: Vec<i64>,
    account_all_trades_ids: Vec<i64>,
    user_stats_ids: Vec<i64>,
    market_stats_all: bool,
    account_orders_subs: Vec<AccountOrdersSubscription>,
    account_all_orders_ids: Vec<i64>,
    on_order_book_update: Option<OrderBookCallback>,
    on_ticker_update: Option<TickerCallback>,
    on_account_update: Option<AccountCallback>,
    on_account_orders_update: Option<AccountOrdersCallback>,
    on_account_all_orders_update: Option<AccountAllOrdersCallback>,
    on_account_all_positions_update: Option<AccountAllPositionsCallback>,
    on_account_all_assets_update: Option<AccountAllAssetsCallback>,
    on_account_spot_avg_entry_prices_update: Option<AccountSpotAvgEntryPricesCallback>,
    on_account_all_trades_update: Option<AccountAllTradesCallback>,
    on_user_stats_update: Option<UserStatsCallback>,
    on_market_stats_update: Option<MarketStatsCallback>,
    order_book_handler: Arc<Mutex<OrderBookHandler>>,
    account_handler: Arc<Mutex<AccountHandler>>,
    account_orders_handler: Arc<Mutex<AccountOrdersHandler>>,
    account_all_positions_handler: Arc<Mutex<AccountAllPositionsHandler>>,
    account_all_assets_handler: Arc<Mutex<AccountAllAssetsHandler>>,
    account_spot_avg_entry_prices_handler: Arc<Mutex<AccountSpotAvgEntryPricesHandler>>,
    account_all_trades_handler: Arc<Mutex<AccountAllTradesHandler>>,
    user_stats_handler: Arc<Mutex<UserStatsHandler>>,
    market_stats_handler: Arc<Mutex<MarketStatsHandler>>,
}

impl WsClient {
    pub fn new(config: &Config) -> Self {
        Self {
            ws_url: config.ws_base_url(),
            auth_token: None,
            order_book_ids: Vec::new(),
            ticker_ids: Vec::new(),
            market_stats_ids: Vec::new(),
            account_ids: Vec::new(),
            account_all_positions_ids: Vec::new(),
            account_all_assets_ids: Vec::new(),
            account_spot_avg_entry_prices_ids: Vec::new(),
            account_all_trades_ids: Vec::new(),
            user_stats_ids: Vec::new(),
            market_stats_all: false,
            account_orders_subs: Vec::new(),
            account_all_orders_ids: Vec::new(),
            on_order_book_update: None,
            on_ticker_update: None,
            on_account_update: None,
            on_account_orders_update: None,
            on_account_all_orders_update: None,
            on_account_all_positions_update: None,
            on_account_all_assets_update: None,
            on_account_spot_avg_entry_prices_update: None,
            on_account_all_trades_update: None,
            on_user_stats_update: None,
            on_market_stats_update: None,
            order_book_handler: Arc::new(Mutex::new(OrderBookHandler::new())),
            account_handler: Arc::new(Mutex::new(AccountHandler::new())),
            account_orders_handler: Arc::new(Mutex::new(AccountOrdersHandler::new())),
            account_all_positions_handler: Arc::new(Mutex::new(AccountAllPositionsHandler::new())),
            account_all_assets_handler: Arc::new(Mutex::new(AccountAllAssetsHandler::new())),
            account_spot_avg_entry_prices_handler: Arc::new(Mutex::new(
                AccountSpotAvgEntryPricesHandler::new(),
            )),
            account_all_trades_handler: Arc::new(Mutex::new(AccountAllTradesHandler::new())),
            user_stats_handler: Arc::new(Mutex::new(UserStatsHandler::new())),
            market_stats_handler: Arc::new(Mutex::new(MarketStatsHandler::new())),
        }
    }

    pub fn with_auth_token(mut self, token: impl Into<String>) -> Self {
        self.auth_token = Some(token.into());
        self
    }

    pub fn subscribe_order_books(mut self, market_ids: Vec<i64>) -> Self {
        self.order_book_ids = market_ids;
        self
    }

    pub fn subscribe_ticker(mut self, market_ids: Vec<i64>) -> Self {
        self.ticker_ids = market_ids;
        self
    }

    pub fn subscribe_market_stats(mut self, market_ids: Vec<i64>) -> Self {
        self.market_stats_ids = market_ids;
        self
    }

    pub fn subscribe_accounts(mut self, account_ids: Vec<i64>) -> Self {
        self.account_ids = account_ids;
        self
    }

    pub fn subscribe_account_all_positions(mut self, account_ids: Vec<i64>) -> Self {
        self.account_all_positions_ids = account_ids;
        self
    }

    pub fn subscribe_account_all_assets(mut self, account_ids: Vec<i64>) -> Self {
        self.account_all_assets_ids = account_ids;
        self
    }

    pub fn subscribe_account_spot_avg_entry_prices(mut self, account_ids: Vec<i64>) -> Self {
        self.account_spot_avg_entry_prices_ids = account_ids;
        self
    }

    pub fn subscribe_account_all_trades(mut self, account_ids: Vec<i64>) -> Self {
        self.account_all_trades_ids = account_ids;
        self
    }

    pub fn subscribe_account_orders(mut self, market_id: i64, account_id: i64) -> Self {
        self.account_orders_subs.push(AccountOrdersSubscription {
            market_id,
            account_id,
        });
        self
    }

    pub fn subscribe_account_all_orders(mut self, account_ids: Vec<i64>) -> Self {
        self.account_all_orders_ids = account_ids;
        self
    }

    pub fn subscribe_user_stats(mut self, account_ids: Vec<i64>) -> Self {
        self.user_stats_ids = account_ids;
        self
    }

    pub fn subscribe_market_stats_all(mut self) -> Self {
        self.market_stats_all = true;
        self
    }

    pub fn on_order_book_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &WsOrderBookState) + Send + Sync + 'static,
    {
        self.on_order_book_update = Some(Box::new(callback));
        self
    }

    pub fn on_ticker_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, Option<f64>, Option<f64>) + Send + Sync + 'static,
    {
        self.on_ticker_update = Some(Box::new(callback));
        self
    }

    pub fn on_account_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &WsAccountAllUpdate) + Send + Sync + 'static,
    {
        self.on_account_update = Some(Box::new(callback));
        self
    }

    pub fn on_account_orders_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &[Order]) + Send + Sync + 'static,
    {
        self.on_account_orders_update = Some(Box::new(callback));
        self
    }

    pub fn on_account_all_orders_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &HashMap<String, Vec<Order>>) + Send + Sync + 'static,
    {
        self.on_account_all_orders_update = Some(Box::new(callback));
        self
    }

    pub fn on_account_all_positions_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &WsAccountAllPositionsUpdate) + Send + Sync + 'static,
    {
        self.on_account_all_positions_update = Some(Box::new(callback));
        self
    }

    pub fn on_account_all_assets_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &WsAccountAllAssetsUpdate) + Send + Sync + 'static,
    {
        self.on_account_all_assets_update = Some(Box::new(callback));
        self
    }

    pub fn on_account_spot_avg_entry_prices_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &WsAccountSpotAvgEntryPricesUpdate) + Send + Sync + 'static,
    {
        self.on_account_spot_avg_entry_prices_update = Some(Box::new(callback));
        self
    }

    pub fn on_account_all_trades_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &WsAccountAllTradesUpdate) + Send + Sync + 'static,
    {
        self.on_account_all_trades_update = Some(Box::new(callback));
        self
    }

    pub fn on_user_stats_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &WsUserStatsUpdate) + Send + Sync + 'static,
    {
        self.on_user_stats_update = Some(Box::new(callback));
        self
    }

    pub fn on_market_stats_update<F>(mut self, callback: F) -> Self
    where
        F: Fn(i64, &WsMarketStatsUpdate) + Send + Sync + 'static,
    {
        self.on_market_stats_update = Some(Box::new(callback));
        self
    }

    /// Get a reference to the order book handler for reading state.
    pub fn order_book_handler(&self) -> &Arc<Mutex<OrderBookHandler>> {
        &self.order_book_handler
    }

    /// Get a reference to the account handler for reading state.
    pub fn account_handler(&self) -> &Arc<Mutex<AccountHandler>> {
        &self.account_handler
    }

    /// Get a reference to the account orders handler for reading state.
    pub fn account_orders_handler(&self) -> &Arc<Mutex<AccountOrdersHandler>> {
        &self.account_orders_handler
    }

    /// Get a reference to the account-all-positions handler for reading state.
    pub fn account_all_positions_handler(&self) -> &Arc<Mutex<AccountAllPositionsHandler>> {
        &self.account_all_positions_handler
    }

    /// Get a reference to the account-all-assets handler for reading state.
    pub fn account_all_assets_handler(&self) -> &Arc<Mutex<AccountAllAssetsHandler>> {
        &self.account_all_assets_handler
    }

    /// Get a reference to the account-spot-avg-entry-prices handler for reading state.
    pub fn account_spot_avg_entry_prices_handler(
        &self,
    ) -> &Arc<Mutex<AccountSpotAvgEntryPricesHandler>> {
        &self.account_spot_avg_entry_prices_handler
    }

    /// Get a reference to the account-all-trades handler for reading state.
    pub fn account_all_trades_handler(&self) -> &Arc<Mutex<AccountAllTradesHandler>> {
        &self.account_all_trades_handler
    }

    /// Get a reference to the user stats handler for reading state.
    pub fn user_stats_handler(&self) -> &Arc<Mutex<UserStatsHandler>> {
        &self.user_stats_handler
    }

    /// Get a reference to the market stats handler for reading state.
    pub fn market_stats_handler(&self) -> &Arc<Mutex<MarketStatsHandler>> {
        &self.market_stats_handler
    }

    /// Connect and run the WebSocket message loop.
    /// This method blocks until the connection is closed or an error occurs.
    pub async fn run(&self) -> Result<()> {
        if !self.has_subscriptions() {
            return Err(SdkError::Other("No subscriptions provided".into()));
        }

        let (ws_stream, _) = connect_async(&self.ws_url).await?;
        let (mut write, mut read) = ws_stream.split();
        let mut keepalive = time::interval(WS_KEEPALIVE_INTERVAL);
        keepalive.set_missed_tick_behavior(MissedTickBehavior::Delay);
        keepalive.tick().await;

        loop {
            tokio::select! {
                _ = keepalive.tick() => {
                    self.send_keepalive(&mut write).await?;
                }
                maybe_msg = read.next() => {
                    let Some(msg) = maybe_msg else {
                        break;
                    };
                    let msg = msg?;
                    match msg {
                        Message::Text(text) => {
                            let parsed: serde_json::Value =
                                serde_json::from_str(&text)?;
                            let msg_type = parsed
                                .get("type")
                                .and_then(|t| t.as_str())
                                .unwrap_or("");
                            let channel = parsed
                                .get("channel")
                                .and_then(|v| v.as_str())
                                .unwrap_or("?");

                            match msg_type {
                                "connected" => {
                                    self.send_subscriptions(&mut write).await?;
                                }
                                "ping" => {
                                    let pong = serde_json::json!({"type": "pong"});
                                    write
                                        .send(Message::Text(pong.to_string().into()))
                                        .await
                                        .map_err(SdkError::from)?;
                                }
                                "subscribed/order_book" => {
                                    match serde_json::from_value::<WsOrderBookMessage>(
                                        parsed.clone(),
                                    ) {
                                        Ok(msg) => {
                                            self.handle_order_book_snapshot(&msg).await
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode order_book snapshot"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode order_book snapshot payload"
                                            );
                                        }
                                    }
                                }
                                "update/order_book" => {
                                    match serde_json::from_value::<WsOrderBookMessage>(
                                        parsed.clone(),
                                    ) {
                                        Ok(msg) => {
                                            self.handle_order_book_update(&msg).await?;
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode order_book update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode order_book update payload"
                                            );
                                        }
                                    }
                                }
                                "subscribed/ticker" | "update/ticker" => {
                                    match serde_json::from_value::<WsTickerUpdate>(
                                        parsed.clone(),
                                    ) {
                                        Ok(msg) => self.handle_ticker_update(&msg),
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode ticker update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode ticker update payload"
                                            );
                                        }
                                    }
                                }
                                "subscribed/account_all" | "update/account_all" => {
                                    match serde_json::from_value::<WsAccountAllUpdate>(
                                        parsed.clone(),
                                    ) {
                                        Ok(msg) => {
                                            self.handle_account_update(&msg).await
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode account_all update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode account_all update payload"
                                            );
                                        }
                                    }
                                }
                                "subscribed/account_all_positions"
                                | "update/account_all_positions" => {
                                    match serde_json::from_value::<
                                        WsAccountAllPositionsUpdate,
                                    >(parsed.clone())
                                    {
                                        Ok(msg) => {
                                            self.handle_account_all_positions_update(
                                                &msg,
                                            )
                                            .await
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode account_all_positions update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode account_all_positions update payload"
                                            );
                                        }
                                    }
                                }
                                "subscribed/account_all_assets"
                                | "update/account_all_assets" => {
                                    match serde_json::from_value::<
                                        WsAccountAllAssetsUpdate,
                                    >(parsed.clone())
                                    {
                                        Ok(msg) => {
                                            self.handle_account_all_assets_update(
                                                &msg,
                                            )
                                            .await
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode account_all_assets update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode account_all_assets update payload"
                                            );
                                        }
                                    }
                                }
                                "subscribed/account_spot_avg_entry_prices"
                                | "update/account_spot_avg_entry_prices" => {
                                    match serde_json::from_value::<
                                        WsAccountSpotAvgEntryPricesUpdate,
                                    >(parsed.clone())
                                    {
                                        Ok(msg) => {
                                            self.handle_account_spot_avg_entry_prices_update(
                                                &msg,
                                            )
                                            .await
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode account_spot_avg_entry_prices update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode account_spot_avg_entry_prices update payload"
                                            );
                                        }
                                    }
                                }
                                "subscribed/account_all_trades"
                                | "update/account_all_trades" => {
                                    match serde_json::from_value::<
                                        WsAccountAllTradesUpdate,
                                    >(parsed.clone())
                                    {
                                        Ok(msg) => {
                                            self.handle_account_all_trades_update(
                                                &msg,
                                            )
                                            .await
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode account_all_trades update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode account_all_trades update payload"
                                            );
                                        }
                                    }
                                }
                                "subscribed/user_stats" | "update/user_stats" => {
                                    match serde_json::from_value::<WsUserStatsUpdate>(
                                        parsed.clone(),
                                    ) {
                                        Ok(msg) => {
                                            self.handle_user_stats_update(&msg).await
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode user_stats update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode user_stats update payload"
                                            );
                                        }
                                    }
                                }
                                "subscribed/market_stats" | "update/market_stats" => {
                                    let updates = parse_market_stats_updates(&parsed);
                                    if updates.is_empty() {
                                        tracing::warn!(
                                            msg_type = msg_type,
                                            channel = channel,
                                            "Failed to decode market_stats update"
                                        );
                                        tracing::debug!(
                                            payload = %parsed,
                                            "Failed to decode market_stats update payload"
                                        );
                                    } else {
                                        for msg in updates {
                                            self.handle_market_stats_update(&msg).await;
                                        }
                                    }
                                }
                                "subscribed/account_orders"
                                | "update/account_orders" => {
                                    match serde_json::from_value::<WsAccountOrdersUpdate>(
                                        parsed.clone(),
                                    ) {
                                        Ok(msg) => {
                                            self.handle_account_orders_update(&msg)
                                                .await
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode account_orders update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode account_orders update payload"
                                            );
                                        }
                                    }
                                }
                                "subscribed/account_all_orders"
                                | "update/account_all_orders" => {
                                    match serde_json::from_value::<
                                        WsAccountAllOrdersUpdate,
                                    >(parsed.clone())
                                    {
                                        Ok(msg) => {
                                            self.handle_account_all_orders_update(&msg)
                                                .await
                                        }
                                        Err(err) => {
                                            tracing::warn!(
                                                err = %err,
                                                msg_type = msg_type,
                                                channel = channel,
                                                "Failed to decode account_all_orders update"
                                            );
                                            tracing::debug!(
                                                err = %err,
                                                payload = %parsed,
                                                "Failed to decode account_all_orders update payload"
                                            );
                                        }
                                    }
                                }
                                _ => {
                                    tracing::debug!(
                                        "Unhandled WS message type: {msg_type}"
                                    );
                                }
                            }
                        }
                        Message::Ping(data) => {
                            write
                                .send(Message::Pong(data))
                                .await
                                .map_err(SdkError::from)?;
                        }
                        Message::Close(_) => break,
                        _ => {}
                    }
                }
            }
        }

        Ok(())
    }

    async fn send_keepalive(&self, write: &mut WsWriteSink) -> Result<()> {
        write
            .send(Message::Ping(Bytes::new()))
            .await
            .map_err(SdkError::from)?;

        // Some quiet authenticated channels appear to be dropped unless the
        // server also sees an application-level frame, so send a lightweight
        // text heartbeat in addition to the WS control ping.
        write
            .send(Message::Text(
                serde_json::json!({"type": "pong"}).to_string().into(),
            ))
            .await
            .map_err(SdkError::from)
    }

    async fn send_subscriptions(&self, write: &mut WsWriteSink) -> Result<()> {
        for msg in self.subscription_messages() {
            write
                .send(Message::Text(msg.to_string().into()))
                .await
                .map_err(SdkError::from)?;
        }
        Ok(())
    }

    fn has_subscriptions(&self) -> bool {
        !self.order_book_ids.is_empty()
            || !self.ticker_ids.is_empty()
            || !self.market_stats_ids.is_empty()
            || !self.account_ids.is_empty()
            || !self.account_all_positions_ids.is_empty()
            || !self.account_all_assets_ids.is_empty()
            || !self.account_spot_avg_entry_prices_ids.is_empty()
            || !self.account_all_trades_ids.is_empty()
            || !self.user_stats_ids.is_empty()
            || self.market_stats_all
            || !self.account_orders_subs.is_empty()
            || !self.account_all_orders_ids.is_empty()
    }

    fn subscription_messages(&self) -> Vec<serde_json::Value> {
        let mut messages = Vec::new();

        for market_id in &self.order_book_ids {
            messages.push(serde_json::json!({
                "type": "subscribe",
                "channel": format!("order_book/{market_id}")
            }));
        }
        for market_id in &self.ticker_ids {
            messages.push(serde_json::json!({
                "type": "subscribe",
                "channel": format!("ticker/{market_id}")
            }));
        }
        for market_id in &self.market_stats_ids {
            messages.push(serde_json::json!({
                "type": "subscribe",
                "channel": format!("market_stats/{market_id}")
            }));
        }
        for account_id in &self.account_ids {
            messages.push(serde_json::json!({
                "type": "subscribe",
                "channel": format!("account_all/{account_id}")
            }));
        }
        for account_id in &self.account_all_positions_ids {
            messages.push(
                self.authed_subscription_message(format!("account_all_positions/{account_id}")),
            );
        }
        for account_id in &self.account_all_assets_ids {
            messages
                .push(self.authed_subscription_message(format!("account_all_assets/{account_id}")));
        }
        for account_id in &self.account_spot_avg_entry_prices_ids {
            messages.push(self.authed_subscription_message(format!(
                "account_spot_avg_entry_prices/{account_id}"
            )));
        }
        for account_id in &self.account_all_trades_ids {
            messages
                .push(self.authed_subscription_message(format!("account_all_trades/{account_id}")));
        }
        for account_id in &self.user_stats_ids {
            messages.push(self.authed_subscription_message(format!("user_stats/{account_id}")));
        }
        if self.market_stats_all {
            messages.push(serde_json::json!({
                "type": "subscribe",
                "channel": "market_stats/all"
            }));
        }
        for sub in &self.account_orders_subs {
            messages.push(self.authed_subscription_message(format!(
                "account_orders/{}/{}",
                sub.market_id, sub.account_id
            )));
        }
        for account_id in &self.account_all_orders_ids {
            messages
                .push(self.authed_subscription_message(format!("account_all_orders/{account_id}")));
        }

        messages
    }

    fn authed_subscription_message(&self, channel: String) -> serde_json::Value {
        let mut msg = serde_json::json!({
            "type": "subscribe",
            "channel": channel
        });
        if let Some(ref token) = self.auth_token {
            msg["auth"] = serde_json::Value::String(token.clone());
        }
        msg
    }

    async fn handle_order_book_snapshot(&self, msg: &WsOrderBookMessage) {
        let market_id = match parse_market_id_from_channel(&msg.channel) {
            Some(id) => id,
            None => return,
        };

        let mut handler = self.order_book_handler.lock().await;
        handler.set_snapshot(market_id, WsOrderBookState::from(&msg.order_book));
        if let (Some(cb), Some(state)) = (&self.on_order_book_update, handler.get(market_id)) {
            cb(market_id, state);
        }
    }

    async fn handle_order_book_update(&self, msg: &WsOrderBookMessage) -> Result<()> {
        let market_id = match parse_market_id_from_channel(&msg.channel) {
            Some(id) => id,
            None => return Ok(()),
        };

        let mut handler = self.order_book_handler.lock().await;
        let state = handler
            .apply_update(market_id, &msg.order_book)
            .map_err(|err| {
                SdkError::Other(format!(
                    "failed to apply order book update for market {market_id}: {err}"
                ))
            })?;
        if let Some(cb) = &self.on_order_book_update {
            cb(market_id, state);
        }
        Ok(())
    }

    fn handle_ticker_update(&self, msg: &WsTickerUpdate) {
        let channel = msg.channel.as_deref().unwrap_or("");
        let market_id = match parse_market_id_from_channel(channel) {
            Some(id) => id,
            None => return,
        };

        let (best_bid, best_ask) = match &msg.ticker {
            Some(ticker) => (ticker.b.price, ticker.a.price),
            None => (None, None),
        };

        if let Some(cb) = &self.on_ticker_update {
            cb(market_id, best_bid, best_ask);
        }
    }

    async fn handle_account_update(&self, msg: &WsAccountAllUpdate) {
        let account_id = msg.account;

        let mut handler = self.account_handler.lock().await;
        handler.set_state(account_id, msg.clone());
        if let (Some(cb), Some(state)) = (&self.on_account_update, handler.get(account_id)) {
            cb(account_id, state);
        }
    }

    async fn handle_account_all_positions_update(&self, msg: &WsAccountAllPositionsUpdate) {
        let Some(account_id) = parse_account_id_from_channel(&msg.channel) else {
            tracing::debug!("WS account_all_positions update missing numeric account_id");
            return;
        };

        let mut handler = self.account_all_positions_handler.lock().await;
        handler.set_state(account_id, msg.clone());
        if let (Some(cb), Some(state)) = (
            &self.on_account_all_positions_update,
            handler.get(account_id),
        ) {
            cb(account_id, state);
        }
    }

    async fn handle_account_all_assets_update(&self, msg: &WsAccountAllAssetsUpdate) {
        let Some(account_id) = parse_account_id_from_channel(&msg.channel) else {
            tracing::debug!("WS account_all_assets update missing numeric account_id");
            return;
        };

        let mut handler = self.account_all_assets_handler.lock().await;
        handler.set_state(account_id, msg.clone());
        if let (Some(cb), Some(state)) =
            (&self.on_account_all_assets_update, handler.get(account_id))
        {
            cb(account_id, state);
        }
    }

    async fn handle_account_spot_avg_entry_prices_update(
        &self,
        msg: &WsAccountSpotAvgEntryPricesUpdate,
    ) {
        let Some(account_id) = parse_account_id_from_channel(&msg.channel) else {
            tracing::debug!("WS account_spot_avg_entry_prices update missing numeric account_id");
            return;
        };

        let mut handler = self.account_spot_avg_entry_prices_handler.lock().await;
        handler.set_state(account_id, msg.clone());
        if let (Some(cb), Some(state)) = (
            &self.on_account_spot_avg_entry_prices_update,
            handler.get(account_id),
        ) {
            cb(account_id, state);
        }
    }

    async fn handle_user_stats_update(&self, msg: &WsUserStatsUpdate) {
        let account_id = parse_account_id_from_channel(&msg.channel);
        let Some(account_id) = account_id else {
            tracing::debug!("WS user_stats update missing numeric account_id");
            return;
        };

        let mut handler = self.user_stats_handler.lock().await;
        handler.set_state(account_id, msg.clone());
        if let (Some(cb), Some(state)) = (&self.on_user_stats_update, handler.get(account_id)) {
            cb(account_id, state);
        }
    }

    async fn handle_account_all_trades_update(&self, msg: &WsAccountAllTradesUpdate) {
        let Some(account_id) = parse_account_id_from_channel(&msg.channel) else {
            tracing::debug!("WS account_all_trades update missing numeric account_id");
            return;
        };

        let mut handler = self.account_all_trades_handler.lock().await;
        handler.set_state(account_id, msg.clone());
        if let (Some(cb), Some(state)) =
            (&self.on_account_all_trades_update, handler.get(account_id))
        {
            cb(account_id, state);
        }
    }

    async fn handle_market_stats_update(&self, msg: &WsMarketStatsUpdate) {
        let Some(market) = msg.market.as_ref() else {
            tracing::debug!("WS market_stats update missing market payload");
            return;
        };
        let market_id = market
            .market_id
            .or_else(|| parse_market_id_from_channel(&msg.channel));
        let Some(market_id) = market_id else {
            tracing::debug!("WS market_stats update missing numeric market_id");
            return;
        };

        let mut handler = self.market_stats_handler.lock().await;
        handler.set_state(market_id, msg.clone());
        if let (Some(cb), Some(state)) = (&self.on_market_stats_update, handler.get(market_id)) {
            cb(market_id, state);
        }
    }

    async fn handle_account_orders_update(&self, msg: &WsAccountOrdersUpdate) {
        let market_id = parse_market_id_from_channel(&msg.channel)
            .or_else(|| msg.orders.keys().find_map(|k| parse_market_id_token(k)));
        let Some(market_id) = market_id else {
            tracing::debug!("WS account_orders update missing numeric market_id");
            return;
        };

        let orders: Vec<Order> = msg.orders.values().flatten().cloned().collect();
        let mut handler = self.account_orders_handler.lock().await;
        handler.set_orders(market_id, orders.clone());
        handler.set_orders_for_account(msg.account, market_id, orders);
        if let (Some(cb), Some(orders)) = (&self.on_account_orders_update, handler.get(market_id)) {
            cb(market_id, orders);
        }
    }

    async fn handle_account_all_orders_update(&self, msg: &WsAccountAllOrdersUpdate) {
        let Some(account_id) = parse_account_id_from_channel(&msg.channel) else {
            tracing::debug!("WS account_all_orders update missing numeric account_id");
            return;
        };

        // Update account-scoped per-market handler state.
        let mut handler = self.account_orders_handler.lock().await;
        for (market_key, orders) in &msg.orders {
            if let Some(market_id) = parse_market_id_token(market_key) {
                handler.set_orders_for_account(account_id, market_id, orders.clone());
            }
        }
        drop(handler);

        if let Some(cb) = &self.on_account_all_orders_update {
            cb(account_id, &msg.orders);
        }
    }
}

fn extract_channel_suffix(channel: &str) -> Option<&str> {
    channel.split(':').nth(1)
}

/// Parse market id from strings like "42" or "42/123".
fn parse_market_id_token(s: &str) -> Option<i64> {
    s.split('/').next().and_then(|v| v.parse::<i64>().ok())
}

fn parse_market_id_from_channel(channel: &str) -> Option<i64> {
    if let Some(suffix) = extract_channel_suffix(channel) {
        return parse_market_id_token(suffix);
    }

    channel.split('/').nth(1).and_then(parse_market_id_token)
}

/// Parse account id from channels like "user_stats/54255" or "user_stats:54255".
fn parse_account_id_from_channel(channel: &str) -> Option<i64> {
    if let Some(suffix) = extract_channel_suffix(channel) {
        return suffix.parse::<i64>().ok();
    }
    channel
        .split('/')
        .nth(1)
        .and_then(|s| s.parse::<i64>().ok())
}

fn looks_like_market_stats_payload(value: &serde_json::Value) -> bool {
    let Some(obj) = value.as_object() else {
        return false;
    };
    obj.contains_key("market_id")
        || obj.contains_key("symbol")
        || obj.contains_key("mark_price")
        || obj.contains_key("index_price")
        || obj.contains_key("last_trade_price")
        || obj.contains_key("current_funding_rate")
}

fn parse_market_stats_updates(parsed: &serde_json::Value) -> Vec<WsMarketStatsUpdate> {
    let msg_type = parsed
        .get("type")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let channel = parsed
        .get("channel")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();

    let mut updates = Vec::new();

    let Some(payload) = parsed.get("market_stats").or_else(|| parsed.get("market")) else {
        return updates;
    };

    if looks_like_market_stats_payload(payload) {
        if let Ok(market) = serde_json::from_value::<PerpsMarketStats>(payload.clone()) {
            updates.push(WsMarketStatsUpdate {
                msg_type,
                channel,
                market: Some(market),
            });
        }
        return updates;
    }

    let Some(map) = payload.as_object() else {
        return updates;
    };
    for (market_key, value) in map {
        if !value.is_object() {
            continue;
        }
        let Ok(mut market) = serde_json::from_value::<PerpsMarketStats>(value.clone()) else {
            continue;
        };
        if market.market_id.is_none() {
            market.market_id = market_key.parse::<i64>().ok();
        }
        updates.push(WsMarketStatsUpdate {
            msg_type: msg_type.clone(),
            channel: channel.clone(),
            market: Some(market),
        });
    }

    updates
}

#[cfg(test)]
mod tests {
    use crate::config::Config;

    use super::{WsClient, parse_market_stats_updates};

    #[test]
    fn parse_market_stats_updates_handles_direct_shape() {
        let raw = serde_json::json!({
            "type": "update/market_stats",
            "channel": "market_stats:91",
            "market_stats": {
                "market_id": "91",
                "symbol": "BTC-USDC",
                "mark_price": "108330.8"
            }
        });

        let updates = parse_market_stats_updates(&raw);
        assert_eq!(updates.len(), 1);
        let market = updates[0].market.as_ref().unwrap();
        assert_eq!(market.market_id, Some(91));
        assert_eq!(market.mark_price, Some(108330.8));
    }

    #[test]
    fn parse_market_stats_updates_handles_all_map_shape() {
        let raw = serde_json::json!({
            "type": "update/market_stats",
            "channel": "market_stats:all",
            "market_stats": {
                "2": {
                    "symbol": "SOL",
                    "mark_price": "85.395"
                }
            }
        });

        let updates = parse_market_stats_updates(&raw);
        assert_eq!(updates.len(), 1);
        let market = updates[0].market.as_ref().unwrap();
        assert_eq!(market.market_id, Some(2));
        assert_eq!(market.symbol.as_deref(), Some("SOL"));
        assert_eq!(market.mark_price, Some(85.395));
    }

    #[test]
    fn parse_market_stats_updates_handles_multiple_markets() {
        let raw = serde_json::json!({
            "type": "update/market_stats",
            "channel": "market_stats:all",
            "market_stats": {
                "2": {
                    "symbol": "SOL",
                    "mark_price": "85.395"
                },
                "91": {
                    "symbol": "BTC-USDC",
                    "mark_price": "108330.8"
                }
            }
        });

        let updates = parse_market_stats_updates(&raw);
        assert_eq!(updates.len(), 2);
        assert!(updates.iter().any(|u| {
            let market = u.market.as_ref().unwrap();
            market.market_id == Some(2) && market.mark_price == Some(85.395)
        }));
        assert!(updates.iter().any(|u| {
            let market = u.market.as_ref().unwrap();
            market.market_id == Some(91) && market.mark_price == Some(108330.8)
        }));
    }

    #[test]
    fn subscription_messages_include_direct_market_stats_channels() {
        let config = Config::new("mainnet");
        let client = WsClient::new(&config)
            .subscribe_market_stats(vec![91])
            .subscribe_ticker(vec![91]);

        let messages = client.subscription_messages();

        assert!(
            messages
                .iter()
                .any(|msg| msg["channel"] == serde_json::json!("market_stats/91"))
        );
        assert!(
            messages
                .iter()
                .any(|msg| msg["channel"] == serde_json::json!("ticker/91"))
        );
    }

    #[test]
    fn direct_market_stats_count_as_subscriptions() {
        let config = Config::new("mainnet");
        let client = WsClient::new(&config).subscribe_market_stats(vec![91]);

        assert!(client.has_subscriptions());
    }
}