tradingview-rs 0.2.0

Tradingview datafeed api `tradingview-rs` project.
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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
use futures_util::{
    SinkExt, StreamExt,
    stream::{SplitSink, SplitStream},
};
use iso_currency::Currency;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::{
    fmt::Debug,
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicU64, Ordering},
    },
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokio::{
    net::TcpStream,
    sync::{Mutex, MutexGuard, RwLock, mpsc},
    task::JoinHandle,
    time::timeout,
};
use tokio_tungstenite::{
    MaybeTlsStream, WebSocketStream, connect_async_with_config,
    tungstenite::{
        client::IntoClientRequest,
        protocol::{Message, WebSocketConfig},
    },
};
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, trace, warn};
use url::Url;
use ustr::{Ustr, ustr};

use crate::{
    Error, Interval, MarketAdjustment, Result, SessionType, SocketServerInfo, Timezone,
    chart::{ChartOptions, options::Range},
    live::{
        handler::Handler,
        models::{
            DataServer, Socket, SocketMessage, SocketMessageDe, SocketMessageSer,
            TradingViewDataEvent, WEBSOCKET_HEADERS,
        },
    },
    payload,
    quote::ALL_QUOTE_FIELDS,
    study::StudyConfiguration,
    utils::{parse_packet, symbol_init},
};

// Error recovery configuration
#[derive(Debug, Clone, Copy)]
pub(crate) struct ErrorRecoveryConfig {
    max_consecutive_errors: u64,
    error_reset_interval: Duration,
    max_recovery_attempts: u32,
    backoff_base_delay: Duration,
    backoff_max_delay: Duration,
    connection_timeout: Duration,
    ping_interval: Duration,
    health_check_interval: Duration,
}

impl Default for ErrorRecoveryConfig {
    fn default() -> Self {
        Self {
            max_consecutive_errors: 5,
            error_reset_interval: Duration::from_secs(60),
            max_recovery_attempts: 3,
            backoff_base_delay: Duration::from_millis(100),
            backoff_max_delay: Duration::from_secs(30),
            connection_timeout: Duration::from_secs(30),
            ping_interval: Duration::from_secs(30),
            health_check_interval: Duration::from_secs(60),
        }
    }
}

#[derive(Debug, Clone)]
struct ErrorStats {
    consecutive_errors: Arc<AtomicU64>,
    last_error_time: Arc<RwLock<Option<Instant>>>,
    total_errors: Arc<AtomicU64>,
    recovery_attempts: Arc<AtomicU64>,
    connection_drops: Arc<AtomicU64>,
    last_successful_message: Arc<RwLock<Option<Instant>>>,
    recent_critical_times: Arc<RwLock<[u64; 4]>>,
    recent_critical_count: Arc<AtomicU64>,
}

impl Default for ErrorStats {
    fn default() -> Self {
        Self {
            consecutive_errors: Arc::new(AtomicU64::new(0)),
            last_error_time: Arc::new(RwLock::new(None)),
            total_errors: Arc::new(AtomicU64::new(0)),
            recovery_attempts: Arc::new(AtomicU64::new(0)),
            connection_drops: Arc::new(AtomicU64::new(0)),
            last_successful_message: Arc::new(RwLock::new(Some(Instant::now()))),
            recent_critical_times: Arc::new(RwLock::new([0u64; 4])),
            recent_critical_count: Arc::new(AtomicU64::new(0)),
        }
    }
}

impl ErrorStats {
    fn increment_error(&self) -> u64 {
        let count = self.consecutive_errors.fetch_add(1, Ordering::SeqCst) + 1;
        self.total_errors.fetch_add(1, Ordering::SeqCst);
        count
    }

    fn reset_consecutive(&self) {
        self.consecutive_errors.store(0, Ordering::SeqCst);
    }

    async fn update_last_error_time(&self) {
        let mut last_error = self.last_error_time.write().await;
        *last_error = Some(Instant::now());
    }

    async fn update_last_successful_message(&self) {
        let mut last_success = self.last_successful_message.write().await;
        *last_success = Some(Instant::now());
    }

    async fn record_critical_error(&self, now_secs: u64) {
        let mut times = self.recent_critical_times.write().await;
        times[0] = times[1];
        times[1] = times[2];
        times[2] = times[3];
        times[3] = now_secs;
        self.recent_critical_count.fetch_add(1, Ordering::Relaxed);
    }

    async fn should_reset_consecutive_errors(&self, reset_interval: Duration) -> bool {
        let last_error = self.last_error_time.read().await;
        if let Some(last_time) = *last_error {
            last_time.elapsed() > reset_interval
        } else {
            false
        }
    }

    async fn is_connection_stale(&self, stale_threshold: Duration) -> bool {
        let last_success = self.last_successful_message.read().await;
        if let Some(last_time) = *last_success {
            last_time.elapsed() > stale_threshold
        } else {
            true // No successful messages yet
        }
    }

    fn get_consecutive_errors(&self) -> u64 {
        self.consecutive_errors.load(Ordering::SeqCst)
    }

    async fn get_recent_critical_count(&self, window_secs: u64) -> usize {
        if self.recent_critical_count.load(Ordering::Relaxed) == 0 {
            return 0;
        }
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        if let Ok(times) = self.recent_critical_times.try_read() {
            times
                .iter()
                .filter(|&&t| t > 0 && now.saturating_sub(t) <= window_secs)
                .count()
        } else {
            0
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// Severity classification for WebSocket errors.
///
/// Used by the error recovery system to decide whether to retry, reconnect,
/// or open the circuit breaker.
pub enum ErrorSeverity {
    /// Trace level - very minor, log only
    Trace,
    /// Low severity - log and continue
    Minor,
    /// Medium severity - may trigger recovery actions
    Moderate,
    /// High severity - requires immediate attention and recovery
    Critical,
    /// Fatal - connection should be terminated
    Fatal,
}

// Connection health tracking
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// Health status of a WebSocket connection.
pub enum ConnectionHealth {
    Healthy,
    Degraded,
    Unstable,
    Failed,
}

#[derive(Debug, Clone, Copy)]
struct HealthMetrics {
    health: ConnectionHealth,
    last_ping_time: Option<Instant>,
    avg_response_time: Duration,
}

impl Default for HealthMetrics {
    fn default() -> Self {
        Self {
            health: ConnectionHealth::Healthy,
            last_ping_time: None,
            avg_response_time: Duration::from_millis(0),
        }
    }
}

/// Metadata for a chart data series returned by TradingView.
///
/// Includes the chart session ID and the [`ChartOptions`] used to request it.
///
/// [`ChartOptions`]: crate::chart::ChartOptions
#[derive(Debug, Clone, Default, Deserialize, Serialize, Copy)]
pub struct SeriesInfo {
    pub chart_session: Ustr,
    pub options: ChartOptions,
}

/// The primary WebSocket client for TradingView real-time data.
///
/// Connects to a TradingView data server, authenticates with the provided token,
/// and streams chart data, quotes, and study results via the handler trait.
///
/// # Architecture
///
/// The client uses a channel-based write path (no lock contention on sends)
/// and a dedicated reader task that dispatches parsed messages to the handler.
///
/// # Example
///
/// ```rust,ignore
/// let ws = WebSocketClient::builder()
///     .auth_token("your_token")
///     .server(DataServer::ProData)
///     .handler(my_handler)
///     .build()
///     .await?;
/// ```
pub struct WebSocketClient<T: Handler> {
    pub server: DataServer,
    pub auth_token: Arc<RwLock<Ustr>>,

    handler: T,

    // WebSocket connection
    cancellation: CancellationToken,
    is_closed: Arc<AtomicBool>,

    read: Arc<Mutex<SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,
    /// Channel-based write path — eliminates `Arc<Mutex<SplitSink>>` lock contention.
    /// All outgoing messages are sent on this channel; a dedicated writer task
    /// drains it and writes to the `SplitSink`.
    ///
    /// Wrapped in `Arc<RwLock<>>`: the hot `send()` path acquires a read lock
    /// (concurrent, cheap).  Only `reconnect()` acquires the write lock.
    write_tx: Arc<RwLock<mpsc::Sender<Message>>>,
    /// Handle to the writer task so we can abort it on reconnect.
    writer_handle: Arc<Mutex<Option<JoinHandle<()>>>>,
    buffer_size: usize,

    // Enhanced error handling and recovery
    error_stats: ErrorStats,
    error_config: ErrorRecoveryConfig,
    health_metrics: Arc<RwLock<HealthMetrics>>,

    // Circuit breaker state
    circuit_breaker_open: Arc<AtomicBool>,
    circuit_breaker_opened_at: Arc<RwLock<Option<Instant>>>,
}

#[bon::bon]
#[allow(private_interfaces)]
impl<T: Handler> WebSocketClient<T> {
    #[builder]
    pub async fn new(
        auth_token: Option<&str>,
        #[builder(default = DataServer::ProData)] server: DataServer,
        handler: T,
        #[builder(default = 1024*1024)] buffer_size: usize,
        #[builder(default)] error_config: ErrorRecoveryConfig,
    ) -> Result<Arc<Self>> {
        let auth_token = Ustr::from(auth_token.unwrap_or("unauthorized_user_token"));
        let (write, read) = Self::connect(server, Some(buffer_size)).await?;

        let is_closed = Arc::new(AtomicBool::new(false));
        let auth_token = Arc::new(RwLock::new(auth_token));
        let read = Arc::new(Mutex::new(read));

        // Channel-based write path: 1024 messages of buffering before backpressure.
        let (write_tx, write_rx) = mpsc::channel(1024);
        let write_tx = Arc::new(RwLock::new(write_tx));
        let writer_handle = Arc::new(Mutex::new(None::<JoinHandle<()>>));

        let client = Arc::new(Self {
            handler,
            server,
            read,
            write_tx: write_tx.clone(),
            writer_handle: writer_handle.clone(),
            auth_token,
            is_closed: is_closed.clone(),
            buffer_size,
            cancellation: CancellationToken::new(),
            error_stats: ErrorStats::default(),
            error_config,
            health_metrics: Arc::new(RwLock::new(HealthMetrics::default())),
            circuit_breaker_open: Arc::new(AtomicBool::new(false)),
            circuit_breaker_opened_at: Arc::new(RwLock::new(None)),
        });

        // Spawn the dedicated writer task.
        Self::spawn_writer(write, write_rx, writer_handle, is_closed.clone());

        // Start health monitoring task
        client.spawn_health_monitor();

        Ok(client)
    }

    pub fn spawn_reader_task(self: Arc<Self>) {
        tokio::spawn(async move {
            if let Err(e) = self.subscribe().await {
                error!("Reader task failed: {}", e);
            }
        });
    }

    /// Spawn a dedicated writer task that owns the `SplitSink` directly (no
    /// `Mutex`) and drains the mpsc channel.  Eliminates write lock contention.
    fn spawn_writer(
        mut sink: SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>,
        mut rx: mpsc::Receiver<Message>,
        handle_storage: Arc<Mutex<Option<JoinHandle<()>>>>,
        is_closed: Arc<AtomicBool>,
    ) {
        let handle = tokio::spawn(async move {
            while let Some(msg) = rx.recv().await {
                if is_closed.load(Ordering::Relaxed) {
                    break;
                }
                if sink.send(msg).await.is_err() {
                    is_closed.store(true, Ordering::Relaxed);
                    break;
                }
            }
            // Channel closed or connection dead — close the sink.
            let _ = sink.close().await;
            is_closed.store(true, Ordering::Relaxed);
        });

        // Store the handle so reconnect can abort it.
        tokio::spawn(async move {
            let mut guard = handle_storage.lock().await;
            *guard = Some(handle);
        });
    }

    async fn connect(
        server: DataServer,
        buffer_size: Option<usize>,
    ) -> Result<(
        SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>,
        SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>,
    )> {
        let url = Url::parse(&format!(
            "wss://{server}.tradingview.com/socket.io/websocket"
        ))?;

        let buffer_size = buffer_size.unwrap_or(1024 * 1024);

        let mut request = url.into_client_request()?;
        request.headers_mut().extend((*WEBSOCKET_HEADERS).clone());

        // Configure WebSocket with larger message size limits
        let conf = WebSocketConfig::default()
            .read_buffer_size(buffer_size)
            .write_buffer_size(buffer_size);

        let (socket, response) = connect_async_with_config(request, Some(conf), false).await?;

        info!("WebSocket connected with status: {}", response.status());

        let (write, read) = socket.split();

        Ok((write, read))
    }

    /// Classify error severity for appropriate response
    async fn classify_error_severity(&self, error: &Error, context: &str) -> ErrorSeverity {
        // Check recent error pattern for escalation
        let consecutive_errors = self.error_stats.get_consecutive_errors();
        let recent_critical = self.error_stats.get_recent_critical_count(300).await;

        // Pattern-based escalation
        let base_severity = match error {
            Error::WebSocket(msg) => {
                if msg.contains("ConnectionClosed") || msg.contains("ConnectionReset") {
                    ErrorSeverity::Critical
                } else if msg.contains("timeout") || msg.contains("WouldBlock") {
                    ErrorSeverity::Moderate
                } else if msg.contains("Protocol") {
                    ErrorSeverity::Critical
                } else {
                    ErrorSeverity::Moderate
                }
            }

            Error::TradingView { source } => {
                use crate::error::TradingViewError;
                match source {
                    TradingViewError::CriticalError => ErrorSeverity::Fatal,
                    TradingViewError::ProtocolError => ErrorSeverity::Critical,
                    TradingViewError::SymbolError | TradingViewError::SeriesError => {
                        ErrorSeverity::Minor
                    }
                    _ => ErrorSeverity::Trace,
                }
            }

            Error::JsonParse(_) => {
                if consecutive_errors > 3 {
                    ErrorSeverity::Moderate
                } else {
                    ErrorSeverity::Minor
                }
            }

            Error::Internal(msg) => {
                if msg.contains("connection") || msg.contains("timeout") {
                    ErrorSeverity::Critical
                } else if context.contains("critical") {
                    ErrorSeverity::Fatal
                } else {
                    ErrorSeverity::Moderate
                }
            }

            _ => ErrorSeverity::Moderate,
        };

        // Escalate based on error patterns
        if recent_critical >= 3 {
            ErrorSeverity::Fatal
        } else if consecutive_errors >= self.error_config.max_consecutive_errors {
            std::cmp::max(base_severity, ErrorSeverity::Critical)
        } else {
            base_severity
        }
    }

    async fn attempt_error_recovery(&self, severity: ErrorSeverity, error: &Error) -> Result<bool> {
        // Check circuit breaker
        if self.is_circuit_breaker_open().await {
            warn!("Circuit breaker is open, skipping recovery attempt");
            return Ok(false);
        }

        match severity {
            ErrorSeverity::Trace => {
                trace!("Trace level error, no action needed: {}", error);
                Ok(true)
            }

            ErrorSeverity::Minor => {
                debug!("Minor error occurred, continuing: {}", error);
                Ok(true)
            }

            ErrorSeverity::Moderate => {
                warn!(
                    "Moderate error occurred, attempting soft recovery: {}",
                    error
                );

                // Reset error count if enough time has passed
                if self
                    .error_stats
                    .should_reset_consecutive_errors(self.error_config.error_reset_interval)
                    .await
                {
                    self.error_stats.reset_consecutive();
                    info!("Reset consecutive error count after timeout period");
                }

                // Health check
                if let Err(health_err) = self.perform_health_check().await {
                    warn!("Health check failed during recovery: {}", health_err);
                    return Ok(false);
                }

                Ok(true)
            }

            ErrorSeverity::Critical => {
                error!(
                    "Critical error occurred, attempting reconnection: {}",
                    error
                );
                self.error_stats
                    .recovery_attempts
                    .fetch_add(1, Ordering::SeqCst);

                // Try recovery with exponential backoff
                for attempt in 1..=self.error_config.max_recovery_attempts {
                    let delay = self.calculate_backoff_delay(attempt);
                    warn!("Recovery attempt {} after {:?} delay", attempt, delay);

                    tokio::time::sleep(delay).await;

                    match timeout(self.error_config.connection_timeout, self.reconnect()).await {
                        Ok(Ok(_)) => {
                            info!(
                                "Successfully recovered from critical error (attempt {})",
                                attempt
                            );
                            self.error_stats.reset_consecutive();
                            return Ok(true);
                        }
                        Ok(Err(reconnect_err)) => {
                            error!("Reconnection attempt {} failed: {}", attempt, reconnect_err);
                        }
                        Err(_) => {
                            error!("Reconnection attempt {} timed out", attempt);
                        }
                    }
                }

                // All recovery attempts failed, open circuit breaker
                self.open_circuit_breaker().await;
                Ok(false)
            }

            ErrorSeverity::Fatal => {
                error!("Fatal error occurred, terminating connection: {}", error);
                self.is_closed.store(true, Ordering::Relaxed);
                self.cancellation.cancel();
                self.open_circuit_breaker().await;
                Ok(false)
            }
        }
    }

    /// Calculate exponential backoff delay
    fn calculate_backoff_delay(&self, attempt: u32) -> Duration {
        let delay = self
            .error_config
            .backoff_base_delay
            .mul_f64((2_f64).powi(attempt as i32 - 1));

        std::cmp::min(delay, self.error_config.backoff_max_delay)
    }

    /// Circuit breaker management
    async fn is_circuit_breaker_open(&self) -> bool {
        if !self.circuit_breaker_open.load(Ordering::Relaxed) {
            return false;
        }

        // Check if circuit breaker should be reset
        let opened_at = self.circuit_breaker_opened_at.read().await;
        if let Some(time) = *opened_at {
            if time.elapsed() > Duration::from_secs(300) {
                // 5 minutes
                self.circuit_breaker_open.store(false, Ordering::Relaxed);
                info!("Circuit breaker reset after timeout");
                return false;
            }
        }

        true
    }

    async fn open_circuit_breaker(&self) {
        self.circuit_breaker_open.store(true, Ordering::Relaxed);
        let mut opened_at = self.circuit_breaker_opened_at.write().await;
        *opened_at = Some(Instant::now());
        error!("Circuit breaker opened due to repeated failures");
    }

    /// health check
    async fn perform_health_check(&self) -> Result<()> {
        if self.is_closed() {
            return Err(Error::Internal(ustr("Connection is closed")));
        }

        // Check if connection is stale
        if self
            .error_stats
            .is_connection_stale(Duration::from_secs(120))
            .await
        {
            warn!("Connection appears stale, performing ping test");
        }

        // Send ping and measure response
        let start = Instant::now();
        self.try_ping().await?;
        let ping_duration = start.elapsed();

        // Update health metrics
        let mut metrics = self.health_metrics.write().await;
        metrics.last_ping_time = Some(start);

        // Update average response time (simple moving average)
        if metrics.avg_response_time.is_zero() {
            metrics.avg_response_time = ping_duration;
        } else {
            metrics.avg_response_time = Duration::from_nanos(
                (metrics.avg_response_time.as_nanos() as f64 * 0.8
                    + ping_duration.as_nanos() as f64 * 0.2) as u64,
            );
        }

        // Determine health status
        metrics.health = if ping_duration > Duration::from_secs(5) {
            ConnectionHealth::Degraded
        } else if self.error_stats.get_consecutive_errors() > 2 {
            ConnectionHealth::Unstable
        } else {
            ConnectionHealth::Healthy
        };

        debug!(
            "Health check completed: {:?}, ping: {:?}",
            metrics.health, ping_duration
        );
        Ok(())
    }

    /// Spawn background health monitoring task
    fn spawn_health_monitor(self: &Arc<Self>) {
        let client = Arc::clone(self);
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(client.error_config.health_check_interval);

            loop {
                tokio::select! {
                    _ = interval.tick() => {
                        if client.is_closed() {
                            break;
                        }

                        if let Err(e) = client.perform_health_check().await {
                            warn!("Scheduled health check failed: {}", e);
                        }
                    }
                    _ = client.cancellation.cancelled() => {
                        debug!("Health monitor task cancelled");
                        break;
                    }
                }
            }
        });
    }

    /// Enhanced error notification with context
    async fn notify_error_handlers(&self, error: &Error, context: &str, severity: ErrorSeverity) {
        // Record error in history
        if severity >= ErrorSeverity::Critical {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            self.error_stats.record_critical_error(now).await;
        }

        // Create comprehensive context information
        let health_metrics = self.health_metrics.read().await;
        let error_context = vec![json!({
            "error_type": format!("{:?}", error),
            "context": context,
            "severity": format!("{:?}", severity),
            "consecutive_errors": self.error_stats.get_consecutive_errors(),
            "total_errors": self.error_stats.total_errors.load(Ordering::SeqCst),
            "recovery_attempts": self.error_stats.recovery_attempts.load(Ordering::SeqCst),
            "connection_health": format!("{:?}", health_metrics.health),
            "avg_response_time_ms": health_metrics.avg_response_time.as_millis(),
            "circuit_breaker_open": self.circuit_breaker_open.load(Ordering::Relaxed),
            "timestamp": chrono::Utc::now().to_rfc3339(),
        })];

        // Notify through the error callback
        self.handler.notify_error(*error, &error_context);
    }

    /// Enhanced error logging with structured information
    fn log_error(&self, error: &Error, context: &str, severity: &ErrorSeverity) {
        let consecutive = self.error_stats.get_consecutive_errors();
        let total = self.error_stats.total_errors.load(Ordering::SeqCst);
        let recovery_attempts = self.error_stats.recovery_attempts.load(Ordering::SeqCst);

        let error_info = format!(
            "{} (consecutive: {}, total: {}, recovery_attempts: {})",
            error, consecutive, total, recovery_attempts
        );

        match severity {
            ErrorSeverity::Trace => {
                trace!("Trace error in {}: {}", context, error_info);
            }
            ErrorSeverity::Minor => {
                debug!("Minor error in {}: {}", context, error_info);
            }
            ErrorSeverity::Moderate => {
                warn!("Moderate error in {}: {}", context, error_info);
            }
            ErrorSeverity::Critical => {
                error!("Critical error in {}: {}", context, error_info);
            }
            ErrorSeverity::Fatal => {
                error!("FATAL error in {}: {}", context, error_info);
            }
        }
    }

    pub fn is_closed(&self) -> bool {
        self.is_closed.load(Ordering::Relaxed)
    }

    pub async fn reconnect(&self) -> Result<()> {
        let auth_token = self.auth_token.read().await;

        // Abort the old writer task.
        let mut wh = self.writer_handle.lock().await;
        if let Some(handle) = wh.take() {
            handle.abort();
        }
        drop(wh);

        let (write, read) = Self::connect(self.server, Some(self.buffer_size)).await?;

        // Create a new channel and spawn a new writer task.
        let (new_tx, new_rx) = mpsc::channel(1024);
        Self::spawn_writer(
            write,
            new_rx,
            self.writer_handle.clone(),
            self.is_closed.clone(),
        );

        // Atomically swap the sender so future writes go to the new connection.
        {
            let mut tx_guard = self.write_tx.write().await;
            *tx_guard = new_tx;
        }

        let mut read_guard = self.read.lock().await;
        *read_guard = read;
        self.is_closed.store(false, Ordering::Relaxed);
        self.set_auth_token(&auth_token).await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn send_raw_message(&self, message: &str) -> Result<()> {
        if self.is_closed.load(Ordering::Relaxed) {
            return Err(Error::Internal("WebSocket is closed".into()));
        }

        // Check circuit breaker
        if self.is_circuit_breaker_open().await {
            return Err(Error::Internal("Circuit breaker is open".into()));
        }

        let tx = self.write_tx.read().await;
        match timeout(
            Duration::from_secs(10),
            tx.send(Message::Text(message.into())),
        )
        .await
        {
            Ok(Ok(_)) => {
                self.error_stats.update_last_successful_message().await;
                Ok(())
            }
            Ok(Err(e)) => Err(Error::WebSocket(e.to_string().into())),
            Err(_) => Err(Error::Internal("Send timeout".into())),
        }
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn send(&self, m: &str, p: &[Value]) -> Result<()> {
        if self.is_closed.load(Ordering::Relaxed) {
            return Err(Error::Internal("WebSocket is closed".into()));
        }
        let tx = self.write_tx.read().await;
        tx.send(SocketMessageSer::new(m, p).to_message()?)
            .await
            .map_err(|e| Error::WebSocket(e.to_string().into()))?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn ping(&self, ping: &Message) -> Result<()> {
        let tx = self.write_tx.read().await;
        tx.send(ping.clone())
            .await
            .map_err(|e| Error::WebSocket(e.to_string().into()))?;
        if ping.is_close() {
            self.is_closed.store(true, Ordering::Relaxed);
            tracing::warn!("ping message is close, closing session");
        }
        Ok(())
    }

    pub async fn close(&self) -> Result<()> {
        self.is_closed.store(true, Ordering::Relaxed);
        // Drop the send half of the channel — this signals the writer task
        // that no more messages are coming, causing `rx.recv()` to return
        // `None` and the writer task to exit.
        let (dummy_tx, _dummy_rx) = mpsc::channel::<Message>(1);
        let mut tx_guard = self.write_tx.write().await;
        let old_tx = std::mem::replace(&mut *tx_guard, dummy_tx);
        drop(old_tx); // closes the old channel
        drop(tx_guard);
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn fast_symbols(&self, quote_session: &str, symbols: &[&str]) -> Result<()> {
        let mut payloads = payload![quote_session];
        payloads.extend(symbols.iter().map(|s| Value::from(*s)));
        self.send("quote_fast_symbols", &payloads).await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn create_quote_session(&self, quote_session: &str) -> Result<()> {
        self.send("quote_create_session", &payload!(quote_session))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn delete_quote_session(&self, quote_session: &str) -> Result<()> {
        self.send("quote_delete_session", &payload!(quote_session))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn set_fields(&self, quote_session: &str) -> Result<()> {
        let mut quote_fields = payload![quote_session];
        quote_fields.extend(ALL_QUOTE_FIELDS.iter().copied().map(|s| Value::from(s)));
        self.send("quote_set_fields", &quote_fields).await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn add_symbols(&self, quote_session: &str, symbols: &[&str]) -> Result<()> {
        let mut payloads = payload![quote_session];
        payloads.extend(symbols.iter().map(|s| Value::from(*s)));
        self.send("quote_add_symbols", &payloads).await?;
        info!("Added {} symbols to quote session", symbols.len());
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn remove_symbols(&self, quote_session: &str, symbols: &[&str]) -> Result<()> {
        let mut payloads = payload![quote_session];
        payloads.extend(symbols.iter().map(|s| Value::from(*s)));
        self.send("quote_remove_symbols", &payloads).await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn set_auth_token(&self, auth_token: &str) -> Result<()> {
        let mut auth_token_ = self.auth_token.write().await;
        *auth_token_ = ustr(auth_token);
        self.send("set_auth_token", &payload!(auth_token)).await?;
        Ok(())
    }

    /// Example: locale = ("en", "US")
    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn set_locale(&self, language_code: &str, country: &str) -> Result<()> {
        self.send("set_locale", &payload!(language_code, country))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn set_data_quality(&self, data_quality: &str) -> Result<()> {
        self.send("set_data_quality", &payload!(data_quality))
            .await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn set_timezone(&self, chart_session: &str, timezone: Timezone) -> Result<()> {
        self.send(
            "switch_timezone",
            &payload!(chart_session, timezone.to_string()),
        )
        .await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn create_chart_session(&self, session: &str) -> Result<()> {
        self.send("chart_create_session", &payload!(session))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    #[builder]
    pub async fn create_series(
        &self,
        chart_session: &str,
        series_identifier: &str, // (sds_2)
        series_id: &str,         // (s1)
        symbol_series_id: &str,  // (sds_sym_2)
        interval: Interval,
        bar_count: u64,
        range: Option<Range>,
    ) -> Result<()> {
        let range = match range {
            Some(r) => r.to_string(),
            None => Default::default(),
        };
        self.send(
            "create_series",
            &payload!(
                chart_session,
                series_identifier,
                series_id,
                symbol_series_id,
                interval.to_string(),
                bar_count,
                range // |r,1626220800:1628640000|1D|5d|1M|3M|6M|YTD|12M|60M|ALL|
            ),
        )
        .await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    #[builder]
    pub async fn modify_series(
        &self,
        chart_session: &str,
        series_identifier: &str, // (sds_2)
        series_id: &str,         // (s1)
        symbol_series_id: &str,  // (sds_sym_2)
        interval: Interval,
        bar_count: u64,
        range: Option<Range>,
    ) -> Result<()> {
        let range = match range {
            Some(r) => r.to_string(),
            None => Default::default(),
        };
        self.send(
            "modify_series",
            &payload!(
                chart_session,
                series_identifier,
                series_id,
                symbol_series_id,
                interval.to_string(),
                bar_count,
                range // |r,1626220800:1628640000|1D|5d|1M|3M|6M|YTD|12M|60M|ALL|
            ),
        )
        .await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn remove_series(&self, chart_session: &str, series_identifier: &str) -> Result<()> {
        self.send("remove_series", &payload!(chart_session, series_identifier))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    #[builder]
    pub async fn resolve_symbol(
        &self,
        session: &str,
        symbol_series_id: &str,
        instrument: &str,
        adjustment: Option<MarketAdjustment>,
        currency: Option<Currency>,
        session_type: Option<SessionType>,
        replay_session: Option<&str>,
    ) -> Result<()> {
        self.send(
            "resolve_symbol",
            &payload!(
                session,
                symbol_series_id,
                symbol_init()
                    .instrument(instrument)
                    .maybe_adjustment(adjustment)
                    .maybe_currency(currency)
                    .maybe_session_type(session_type)
                    .maybe_replay(replay_session)
                    .call()?
            ),
        )
        .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn delete_chart_session(&self, session: &str) -> Result<()> {
        self.send("chart_delete_session", &payload!(session))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn request_more_data(
        &self,
        chart_session: &str,
        series_id: &str,
        num: u64,
    ) -> Result<()> {
        self.send(
            "request_more_data",
            &payload!(chart_session, series_id, num),
        )
        .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn request_more_tickmarks(
        &self,
        chart_session: &str,
        series_id: &str,
        num: u64,
    ) -> Result<()> {
        self.send(
            "request_more_tickmarks",
            &payload!(chart_session, series_id, num),
        )
        .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn create_replay_session(&self, session: &str) -> Result<()> {
        self.send("replay_create_session", &payload!(session))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    #[builder]
    pub async fn add_replay_series(
        &self,
        chart_session: &str,
        series_id: &str,
        instrument: &str, // e.g., "HOSE:FPT"
        adjustment: Option<MarketAdjustment>,
        session_type: Option<SessionType>,
        currency: Option<Currency>,
        interval: Interval,
    ) -> Result<()> {
        self.send(
            "replay_add_series",
            &payload!(
                chart_session,
                series_id,
                symbol_init()
                    .instrument(instrument)
                    .maybe_adjustment(adjustment)
                    .maybe_currency(currency)
                    .maybe_session_type(session_type)
                    .call()?,
                interval.to_string()
            ),
        )
        .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn delete_replay_session(&self, session: &str) -> Result<()> {
        self.send("replay_delete_session", &payload!(session))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn replay_step(&self, session: &str, series_id: &str, step: u64) -> Result<()> {
        self.send("replay_step", &payload!(session, series_id, step))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn replay_start(
        &self,
        chart_session: &str,
        series_id: &str,
        interval: Interval,
    ) -> Result<()> {
        self.send(
            "replay_start",
            &payload!(chart_session, series_id, interval.to_string()),
        )
        .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn replay_stop(&self, chart_session: &str, series_id: &str) -> Result<()> {
        self.send("replay_stop", &payload!(chart_session, series_id))
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn replay_reset(
        &self,
        chart_session: &str,
        series_id: &str,
        timestamp: i64,
    ) -> Result<()> {
        self.send(
            "replay_reset",
            &payload!(chart_session, series_id, timestamp),
        )
        .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    #[builder]
    pub async fn create_study(
        &self,
        chart_session: &str,
        study_ids: &[&str; 2],
        chart_series_id: &str,
        study: StudyConfiguration,
    ) -> Result<()> {
        let mut payloads: Vec<Value> = vec![
            Value::from(chart_session),
            Value::from(study_ids[0]),
            Value::from(study_ids[1]),
            Value::from(chart_series_id),
        ];

        match study {
            StudyConfiguration::Pine(pine_indicator) => {
                payloads.push(Value::from(pine_indicator.script_type.to_string()));
                payloads.push(pine_indicator.to_study_inputs()?);
            }
            StudyConfiguration::Builtin(study_name, study_config) => {
                payloads.push(Value::from(study_name));
                payloads.push(json!(study_config));
            }
        }

        self.send("create_study", &payloads).await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    #[builder]
    pub async fn modify_study(
        &self,
        chart_session: &str,
        study_ids: &[&str; 2],
        chart_series_id: &str,
        study: StudyConfiguration,
    ) -> Result<()> {
        let mut payloads: Vec<Value> = vec![
            Value::from(chart_session),
            Value::from(study_ids[0]),
            Value::from(study_ids[1]),
            Value::from(chart_series_id),
        ];

        match study {
            StudyConfiguration::Pine(pine_indicator) => {
                payloads.push(Value::from(pine_indicator.script_type.to_string()));
                payloads.push(pine_indicator.to_study_inputs()?);
            }
            StudyConfiguration::Builtin(study_name, study_config) => {
                payloads.push(Value::from(study_name));
                payloads.push(json!(study_config));
            }
        }

        self.send("modify_study", &payloads).await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "debug")]
    pub async fn remove_study(&self, chart_session: &str, study_id: &str) -> Result<()> {
        self.send("remove_study", &payload!(chart_session, study_id))
            .await?;
        Ok(())
    }

    pub async fn delete(&self) -> Result<()> {
        // Close the socket last
        if let Err(e) = self.close().await {
            error!("Failed to close socket: {:?}", e);
            return Err(e);
        }

        debug!("WebSocket client deleted successfully");
        Ok(())
    }

    pub async fn subscribe(&self) -> Result<()> {
        let read = self.read.lock().await;
        if let Err(e) = self.event_loop(read).await {
            error!("Event loop failed: {}", e);
            self.is_closed.store(true, Ordering::Relaxed);
            self.cancellation.cancel();
            return Err(e);
        }
        Ok(())
    }

    pub async fn closed_notifier(&self) {
        self.cancellation.cancelled().await;
    }

    /// Fire-and-forget ping. Ignores `WouldBlock` when write buffer is full.
    pub async fn try_ping(&self) -> Result<()> {
        if self.is_closed() {
            return Ok(());
        }
        self.ping(&Message::Ping(Vec::new().into()))
            .await
            .map_err(|e| Error::WebSocket(ustr(&format!("{e}"))))?;
        Ok(())
    }

    pub async fn get_connection_stats(&self) -> Value {
        let health_metrics = self.health_metrics.read().await;
        let is_closed = self.is_closed();

        json!({
            "consecutive_errors": self.error_stats.get_consecutive_errors(),
            "total_errors": self.error_stats.total_errors.load(Ordering::SeqCst),
            "recovery_attempts": self.error_stats.recovery_attempts.load(Ordering::SeqCst),
            "connection_drops": self.error_stats.connection_drops.load(Ordering::SeqCst),
            "health": format!("{:?}", health_metrics.health),
            "avg_response_time_ms": health_metrics.avg_response_time.as_millis(),
            "circuit_breaker_open": self.circuit_breaker_open.load(Ordering::Relaxed),
            "is_closed": is_closed,
        })
    }
}

impl<T: Handler> Socket for WebSocketClient<T> {
    async fn event_loop(
        &self,
        mut read: MutexGuard<'_, SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>>,
    ) -> Result<()> {
        trace!("WebSocket event loop started");

        let mut ping_interval = tokio::time::interval(self.error_config.ping_interval);
        ping_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

        loop {
            if self.is_closed.load(Ordering::Relaxed) {
                trace!("WebSocket is closed, ending event loop");
                break;
            }

            tokio::select! {
                // Handle incoming messages
                message_result = timeout(Duration::from_secs(30), read.next()) => {
                    match message_result {
                        Ok(Some(Ok(message))) => {
                            trace!("Received message: {:?}", message);
                            if let Err(e) = self.handle_raw_messages(message).await {
                                self.handle_error(e, ustr("handle_raw_messages")).await?;
                            } else {
                                // Reset consecutive errors on successful message processing
                                if self.error_stats.get_consecutive_errors() > 0 {
                                    self.error_stats.reset_consecutive();
                                    debug!("Reset consecutive errors after successful message processing");
                                }
                                self.error_stats.update_last_successful_message().await;
                            }
                        }
                        Ok(Some(Err(e))) => {
                            error!("Error reading message: {:#?}", e);
                            self.error_stats.connection_drops.fetch_add(1, Ordering::SeqCst);
                            self.handle_error(
                                Error::WebSocket(e.to_string().into()),
                                ustr("event_loop_read"),
                            ).await?;

                            // For connection errors, we should break the loop
                            if e.to_string().contains("ConnectionClosed") ||
                               e.to_string().contains("ConnectionReset") {
                                break;
                            }
                        }
                        Ok(None) => {
                            info!("WebSocket stream ended");
                            self.is_closed.store(true, Ordering::Relaxed);
                            break;
                        }
                        Err(_) => {
                            warn!("WebSocket read timeout, checking connection health");
                            if let Err(e) = self.perform_health_check().await {
                                warn!("Health check failed during timeout: {}", e);
                                // Continue trying unless it's a fatal error
                                if matches!(self.classify_error_severity(&e, "health_check").await, ErrorSeverity::Fatal) {
                                    break;
                                }
                            }
                        }
                    }
                }

                // Periodic ping
                _ = ping_interval.tick() => {
                    if !self.is_closed() {
                        if let Err(e) = self.try_ping().await {
                            warn!("Periodic ping failed: {}", e);
                            self.handle_error(e, ustr("periodic_ping")).await?;
                        }
                    }
                }

                // Cancellation
                _ = self.cancellation.cancelled() => {
                    info!("Event loop cancelled");
                    break;
                }
            }
        }

        trace!("WebSocket event loop ended");
        Ok(())
    }

    async fn handle_raw_messages(&self, raw: Message) -> Result<()> {
        match &raw {
            Message::Text(text) => {
                trace!("Received text message: {}", text);
                self.handle_parsed_messages(parse_packet(text), &raw)
                    .await?;
            }
            Message::Close(msg) => {
                warn!("Connection closed with code: {:?}", msg);
                self.is_closed.store(true, Ordering::Relaxed);
                self.cancellation.cancel();
            }
            Message::Binary(msg) => {
                debug!("Received binary message: {:?}", msg);
                // TODO: handle binary messages
            }
            Message::Ping(msg) => {
                trace!("Received ping message: {:?}", msg);
            }
            Message::Pong(msg) => {
                trace!("Received pong message: {:?}", msg);
            }
            Message::Frame(f) => {
                debug!("Received frame message: {:?}", f);
            }
        }
        Ok(())
    }

    async fn handle_parsed_messages(
        &self,
        messages: Vec<SocketMessage<SocketMessageDe>>,
        raw: &Message,
    ) -> Result<()> {
        for message in messages {
            match message {
                SocketMessage::SocketServerInfo(info) => {
                    trace!("received server info: {:?}", info);
                }
                SocketMessage::SocketMessage(msg) => {
                    trace!(
                        "Processing socket message: method={}, params={:?}",
                        msg.m, msg.p
                    );
                    if let Err(e) = self.handle_message_data(msg).await {
                        self.handle_error(e, ustr("handle_message_data")).await?;
                    }
                }
                SocketMessage::Other(value) => {
                    trace!("Received other message: {:?}", value);
                    if value.is_number() {
                        debug!("handling heartbeat message: {:?}", value);
                        if let Err(e) = self.ping(raw).await {
                            self.handle_error(e, ustr("ping_response")).await?;
                        }
                    } else if value.is_string() {
                        trace!("Received string message: {:?}", value);
                    } else if let Ok(server_info) = SocketServerInfo::deserialize(&value) {
                        info!("{}", server_info);
                    } else {
                        warn!("Received unrecognized message: {:?}", value);
                    }
                }
                SocketMessage::Unknown(s) => {
                    warn!("unknown message: {:?}", s);
                }
            }
        }
        Ok(())
    }

    #[tracing::instrument(skip(self), level = "trace")]
    async fn handle_message_data(&self, message: SocketMessageDe) -> Result<()> {
        let event = TradingViewDataEvent::from(message.m);
        self.handler.handle_events(event, &message.p);
        Ok(())
    }

    async fn handle_error(&self, error: Error, context: Ustr) -> Result<()> {
        let context_str = context.as_str();

        // Update error statistics
        let _consecutive_errors = self.error_stats.increment_error();
        self.error_stats.update_last_error_time().await;

        // Classify error severity with pattern detection
        let severity = self.classify_error_severity(&error, context_str).await;

        // Log the error appropriately
        self.log_error(&error, context_str, &severity);

        // Notify error handlers with enhanced context
        self.notify_error_handlers(&error, context_str, severity)
            .await;

        // Handle based on severity
        match severity {
            ErrorSeverity::Trace | ErrorSeverity::Minor => {
                // Continue without recovery
                Ok(())
            }

            ErrorSeverity::Moderate => {
                // Attempt soft recovery
                match self.attempt_error_recovery(severity, &error).await {
                    Ok(true) => Ok(()),
                    Ok(false) => {
                        warn!("Moderate error recovery failed, continuing anyway");
                        Ok(())
                    }
                    Err(recovery_err) => {
                        warn!("Error during moderate recovery: {}", recovery_err);
                        Ok(()) // Don't fail on moderate recovery errors
                    }
                }
            }

            ErrorSeverity::Critical | ErrorSeverity::Fatal => {
                // Attempt recovery or fail
                match self.attempt_error_recovery(severity, &error).await {
                    Ok(recovered) => {
                        if !recovered {
                            error!(
                                "Failed to recover from {} error",
                                if matches!(severity, ErrorSeverity::Critical) {
                                    "critical"
                                } else {
                                    "fatal"
                                }
                            );
                            return Err(Error::Internal(ustr("Error recovery failed")));
                        }
                        Ok(())
                    }
                    Err(recovery_err) => {
                        error!("Error during recovery attempt: {}", recovery_err);
                        Err(recovery_err)
                    }
                }
            }
        }
    }
}