ibapi 2.11.1

A Rust implementation of the Interactive Brokers TWS API, providing a reliable and user friendly interface for TWS and IB Gateway. Designed with a focus on simplicity and performance.
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
//! Message encoding, decoding, and routing for TWS API communication.
//!
//! This module handles the low-level message protocol between the client and TWS,
//! including request/response message formatting, field encoding/decoding,
//! and message type definitions.

use std::fmt::Display;
use std::io::Write;
use std::ops::Index;
use std::str::{self, FromStr};

use byteorder::{BigEndian, WriteBytesExt};

use log::debug;
use serde::{Deserialize, Serialize};
use time::{macros::format_description, Date, OffsetDateTime, PrimitiveDateTime};
use time_tz::{OffsetResult, PrimitiveDateTimeExt, TimeZone, Tz};

use crate::common::timezone::find_timezone;
use crate::{Error, ToField};

pub mod parser_registry;
pub(crate) mod shared_channel_configuration;
#[cfg(test)]
mod tests;

#[cfg(test)]
mod from_str_tests {
    use super::*;
    use std::str::FromStr;

    #[test]
    fn test_outgoing_messages_from_str() {
        // Test some common message types
        assert_eq!(OutgoingMessages::from_str("1").unwrap(), OutgoingMessages::RequestMarketData);
        assert_eq!(OutgoingMessages::from_str("17").unwrap(), OutgoingMessages::RequestManagedAccounts);
        assert_eq!(OutgoingMessages::from_str("49").unwrap(), OutgoingMessages::RequestCurrentTime);
        assert_eq!(OutgoingMessages::from_str("61").unwrap(), OutgoingMessages::RequestPositions);

        // Test error cases
        assert!(OutgoingMessages::from_str("999").is_err());
        assert!(OutgoingMessages::from_str("abc").is_err());
        assert!(OutgoingMessages::from_str("").is_err());
    }

    #[test]
    fn test_outgoing_messages_roundtrip() {
        // Test that we can convert to string and back
        let msg = OutgoingMessages::RequestCurrentTime;
        let as_string = msg.to_string();
        let parsed = OutgoingMessages::from_str(&as_string).unwrap();
        assert_eq!(parsed, OutgoingMessages::RequestCurrentTime);

        // Test with another message type
        let msg = OutgoingMessages::RequestManagedAccounts;
        let as_string = msg.to_string();
        let parsed = OutgoingMessages::from_str(&as_string).unwrap();
        assert_eq!(parsed, OutgoingMessages::RequestManagedAccounts);
    }

    #[test]
    fn test_incoming_messages_from_str() {
        // Test some common message types
        assert_eq!(IncomingMessages::from_str("4").unwrap(), IncomingMessages::Error);
        assert_eq!(IncomingMessages::from_str("15").unwrap(), IncomingMessages::ManagedAccounts);
        assert_eq!(IncomingMessages::from_str("49").unwrap(), IncomingMessages::CurrentTime);
        assert_eq!(IncomingMessages::from_str("61").unwrap(), IncomingMessages::Position);

        // Test NotValid for unknown values
        assert_eq!(IncomingMessages::from_str("999").unwrap(), IncomingMessages::NotValid);
        assert_eq!(IncomingMessages::from_str("0").unwrap(), IncomingMessages::NotValid);
        assert_eq!(IncomingMessages::from_str("-1").unwrap(), IncomingMessages::NotValid);

        // Test error cases for non-numeric strings
        assert!(IncomingMessages::from_str("abc").is_err());
        assert!(IncomingMessages::from_str("").is_err());
        assert!(IncomingMessages::from_str("1.5").is_err());
    }

    #[test]
    fn test_incoming_messages_roundtrip() {
        // Test with CurrentTime message
        let n = 49;
        let msg = IncomingMessages::from(n);
        let as_string = n.to_string();
        let parsed = IncomingMessages::from_str(&as_string).unwrap();
        assert_eq!(parsed, msg);

        // Test with ManagedAccounts message
        let n = 15;
        let msg = IncomingMessages::from(n);
        let as_string = n.to_string();
        let parsed = IncomingMessages::from_str(&as_string).unwrap();
        assert_eq!(parsed, msg);

        // Test with NotValid (unknown value)
        let n = 999;
        let msg = IncomingMessages::from(n);
        let as_string = n.to_string();
        let parsed = IncomingMessages::from_str(&as_string).unwrap();
        assert_eq!(parsed, msg);
        assert_eq!(parsed, IncomingMessages::NotValid);
    }
}

const INFINITY_STR: &str = "Infinity";
const UNSET_DOUBLE: &str = "1.7976931348623157E308";
const UNSET_INTEGER: &str = "2147483647";
const UNSET_LONG: &str = "9223372036854775807";

/// Messages emitted by TWS/Gateway over the market data socket.
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum IncomingMessages {
    /// Gateway initiated shutdown.
    Shutdown = -2,
    /// Unknown or unsupported message id.
    NotValid = -1,
    /// Tick price update.
    TickPrice = 1,
    /// Tick size update.
    TickSize = 2,
    /// Order status update.
    OrderStatus = 3,
    /// Error (includes request id and code).
    Error = 4,
    /// Open order description.
    OpenOrder = 5,
    /// Account value key/value pair.
    AccountValue = 6,
    /// Portfolio value line.
    PortfolioValue = 7,
    /// Account update timestamp.
    AccountUpdateTime = 8,
    /// Next valid order id notification.
    NextValidId = 9,
    /// Contract details payload.
    ContractData = 10,
    /// Execution data update.
    ExecutionData = 11,
    /// Level 1 market depth row update.
    MarketDepth = 12,
    /// Level 2 market depth row update.
    MarketDepthL2 = 13,
    /// News bulletin broadcast.
    NewsBulletins = 14,
    /// List of managed accounts.
    ManagedAccounts = 15,
    /// Financial advisor configuration data.
    ReceiveFA = 16,
    /// Historical bar data payload.
    HistoricalData = 17,
    /// Bond contract details payload.
    BondContractData = 18,
    /// Scanner parameter definitions.
    ScannerParameters = 19,
    /// Scanner subscription results.
    ScannerData = 20,
    /// Option computation tick.
    TickOptionComputation = 21,
    /// Generic numeric tick (e.g. implied volatility).
    TickGeneric = 45,
    /// String-valued tick (exchange names, etc.).
    TickString = 46,
    /// Exchange for Physical tick update.
    TickEFP = 47, //TICK EFP 47
    /// Current world clock time.
    CurrentTime = 49,
    /// Real-time bars update.
    RealTimeBars = 50,
    /// Fundamental data response.
    FundamentalData = 51,
    /// End marker for contract details batches.
    ContractDataEnd = 52,
    /// End marker for open order batches.
    OpenOrderEnd = 53,
    /// End marker for account download.
    AccountDownloadEnd = 54,
    /// End marker for execution data.
    ExecutionDataEnd = 55,
    /// Delta-neutral validation response.
    DeltaNeutralValidation = 56,
    /// End of tick snapshot.
    TickSnapshotEnd = 57,
    /// Market data type acknowledgment.
    MarketDataType = 58,
    /// Commissions report payload.
    CommissionsReport = 59,
    /// Position update.
    Position = 61,
    /// End marker for position updates.
    PositionEnd = 62,
    /// Account summary update.
    AccountSummary = 63,
    /// End marker for account summary stream.
    AccountSummaryEnd = 64,
    /// API verification challenge.
    VerifyMessageApi = 65,
    /// API verification completion.
    VerifyCompleted = 66,
    /// Display group list response.
    DisplayGroupList = 67,
    /// Display group update.
    DisplayGroupUpdated = 68,
    /// Auth + verification challenge.
    VerifyAndAuthMessageApi = 69,
    /// Auth + verification completion.
    VerifyAndAuthCompleted = 70,
    /// Multi-account position update.
    PositionMulti = 71,
    /// End marker for multi-account position stream.
    PositionMultiEnd = 72,
    /// Multi-account account update.
    AccountUpdateMulti = 73,
    /// End marker for multi-account account stream.
    AccountUpdateMultiEnd = 74,
    /// Option security definition parameters.
    SecurityDefinitionOptionParameter = 75,
    /// End marker for option security definition stream.
    SecurityDefinitionOptionParameterEnd = 76,
    /// Soft dollar tier information.
    SoftDollarTier = 77,
    /// Family code response.
    FamilyCodes = 78,
    /// Matching symbol samples.
    SymbolSamples = 79,
    /// Exchanges offering market depth.
    MktDepthExchanges = 80,
    /// Tick request parameter info.
    TickReqParams = 81,
    /// Smart component routing map.
    SmartComponents = 82,
    /// News article content.
    NewsArticle = 83,
    /// News headline tick.
    TickNews = 84,
    /// Available news providers.
    NewsProviders = 85,
    /// Historical news headlines.
    HistoricalNews = 86,
    /// End marker for historical news.
    HistoricalNewsEnd = 87,
    /// Head timestamp for historical data.
    HeadTimestamp = 88,
    /// Histogram data response.
    HistogramData = 89,
    /// Streaming historical data update.
    HistoricalDataUpdate = 90,
    /// Market data request reroute notice.
    RerouteMktDataReq = 91,
    /// Market depth request reroute notice.
    RerouteMktDepthReq = 92,
    /// Market rule response.
    MarketRule = 93,
    /// Account PnL update.
    PnL = 94,
    /// Single position PnL update.
    PnLSingle = 95,
    /// Historical tick data (midpoint).
    HistoricalTick = 96,
    /// Historical tick data (bid/ask).
    HistoricalTickBidAsk = 97,
    /// Historical tick data (trades).
    HistoricalTickLast = 98,
    /// Tick-by-tick streaming data.
    TickByTick = 99,
    /// Order bound notification for API multiple endpoints.
    OrderBound = 100,
    /// Completed order information.
    CompletedOrder = 101,
    /// End marker for completed orders.
    CompletedOrdersEnd = 102,
    /// End marker for FA profile replacement.
    ReplaceFAEnd = 103,
    /// Wall Street Horizon metadata update.
    WshMetaData = 104,
    /// Wall Street Horizon event payload.
    WshEventData = 105,
    /// Historical schedule response.
    HistoricalSchedule = 106,
    /// User information response.
    UserInfo = 107,
    /// End marker for historical data.
    HistoricalDataEnd = 108,
    /// Current time in milliseconds.
    CurrentTimeInMillis = 109,
    /// Configuration response.
    ConfigResponse = 110,
    /// Update configuration response.
    UpdateConfigResponse = 111,
}

impl From<i32> for IncomingMessages {
    fn from(value: i32) -> IncomingMessages {
        match value {
            -2 => IncomingMessages::Shutdown,
            1 => IncomingMessages::TickPrice,
            2 => IncomingMessages::TickSize,
            3 => IncomingMessages::OrderStatus,
            4 => IncomingMessages::Error,
            5 => IncomingMessages::OpenOrder,
            6 => IncomingMessages::AccountValue,
            7 => IncomingMessages::PortfolioValue,
            8 => IncomingMessages::AccountUpdateTime,
            9 => IncomingMessages::NextValidId,
            10 => IncomingMessages::ContractData,
            11 => IncomingMessages::ExecutionData,
            12 => IncomingMessages::MarketDepth,
            13 => IncomingMessages::MarketDepthL2,
            14 => IncomingMessages::NewsBulletins,
            15 => IncomingMessages::ManagedAccounts,
            16 => IncomingMessages::ReceiveFA,
            17 => IncomingMessages::HistoricalData,
            18 => IncomingMessages::BondContractData,
            19 => IncomingMessages::ScannerParameters,
            20 => IncomingMessages::ScannerData,
            21 => IncomingMessages::TickOptionComputation,
            45 => IncomingMessages::TickGeneric,
            46 => IncomingMessages::TickString,
            47 => IncomingMessages::TickEFP, //TICK EFP 47
            49 => IncomingMessages::CurrentTime,
            50 => IncomingMessages::RealTimeBars,
            51 => IncomingMessages::FundamentalData,
            52 => IncomingMessages::ContractDataEnd,
            53 => IncomingMessages::OpenOrderEnd,
            54 => IncomingMessages::AccountDownloadEnd,
            55 => IncomingMessages::ExecutionDataEnd,
            56 => IncomingMessages::DeltaNeutralValidation,
            57 => IncomingMessages::TickSnapshotEnd,
            58 => IncomingMessages::MarketDataType,
            59 => IncomingMessages::CommissionsReport,
            61 => IncomingMessages::Position,
            62 => IncomingMessages::PositionEnd,
            63 => IncomingMessages::AccountSummary,
            64 => IncomingMessages::AccountSummaryEnd,
            65 => IncomingMessages::VerifyMessageApi,
            66 => IncomingMessages::VerifyCompleted,
            67 => IncomingMessages::DisplayGroupList,
            68 => IncomingMessages::DisplayGroupUpdated,
            69 => IncomingMessages::VerifyAndAuthMessageApi,
            70 => IncomingMessages::VerifyAndAuthCompleted,
            71 => IncomingMessages::PositionMulti,
            72 => IncomingMessages::PositionMultiEnd,
            73 => IncomingMessages::AccountUpdateMulti,
            74 => IncomingMessages::AccountUpdateMultiEnd,
            75 => IncomingMessages::SecurityDefinitionOptionParameter,
            76 => IncomingMessages::SecurityDefinitionOptionParameterEnd,
            77 => IncomingMessages::SoftDollarTier,
            78 => IncomingMessages::FamilyCodes,
            79 => IncomingMessages::SymbolSamples,
            80 => IncomingMessages::MktDepthExchanges,
            81 => IncomingMessages::TickReqParams,
            82 => IncomingMessages::SmartComponents,
            83 => IncomingMessages::NewsArticle,
            84 => IncomingMessages::TickNews,
            85 => IncomingMessages::NewsProviders,
            86 => IncomingMessages::HistoricalNews,
            87 => IncomingMessages::HistoricalNewsEnd,
            88 => IncomingMessages::HeadTimestamp,
            89 => IncomingMessages::HistogramData,
            90 => IncomingMessages::HistoricalDataUpdate,
            91 => IncomingMessages::RerouteMktDataReq,
            92 => IncomingMessages::RerouteMktDepthReq,
            93 => IncomingMessages::MarketRule,
            94 => IncomingMessages::PnL,
            95 => IncomingMessages::PnLSingle,
            96 => IncomingMessages::HistoricalTick,
            97 => IncomingMessages::HistoricalTickBidAsk,
            98 => IncomingMessages::HistoricalTickLast,
            99 => IncomingMessages::TickByTick,
            100 => IncomingMessages::OrderBound,
            101 => IncomingMessages::CompletedOrder,
            102 => IncomingMessages::CompletedOrdersEnd,
            103 => IncomingMessages::ReplaceFAEnd,
            104 => IncomingMessages::WshMetaData,
            105 => IncomingMessages::WshEventData,
            106 => IncomingMessages::HistoricalSchedule,
            107 => IncomingMessages::UserInfo,
            108 => IncomingMessages::HistoricalDataEnd,
            109 => IncomingMessages::CurrentTimeInMillis,
            110 => IncomingMessages::ConfigResponse,
            111 => IncomingMessages::UpdateConfigResponse,
            _ => IncomingMessages::NotValid,
        }
    }
}

impl FromStr for IncomingMessages {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.parse::<i32>() {
            Ok(n) => Ok(IncomingMessages::from(n)),
            Err(_) => Err(Error::Simple(format!("Invalid incoming message type: {}", s))),
        }
    }
}

/// Return the message field index containing the order id, if present.
pub fn order_id_index(kind: IncomingMessages) -> Option<usize> {
    match kind {
        IncomingMessages::OpenOrder | IncomingMessages::OrderStatus => Some(1),
        IncomingMessages::ExecutionData | IncomingMessages::ExecutionDataEnd => Some(2),
        _ => None,
    }
}

/// Return the message field index containing the request id, if present.
pub fn request_id_index(kind: IncomingMessages) -> Option<usize> {
    match kind {
        IncomingMessages::AccountSummary => Some(2),
        IncomingMessages::AccountSummaryEnd => Some(2),
        IncomingMessages::AccountUpdateMulti => Some(2),
        IncomingMessages::AccountUpdateMultiEnd => Some(2),
        IncomingMessages::ContractData => Some(1),
        IncomingMessages::ContractDataEnd => Some(2),
        // Error uses version-dependent indices; use ResponseMessage::error_request_id() instead.
        IncomingMessages::ExecutionData => Some(1),
        IncomingMessages::ExecutionDataEnd => Some(2),
        IncomingMessages::HeadTimestamp => Some(1),
        IncomingMessages::HistogramData => Some(1),
        IncomingMessages::HistoricalData => Some(1),
        IncomingMessages::HistoricalDataEnd => Some(1),
        IncomingMessages::HistoricalDataUpdate => Some(1),
        IncomingMessages::HistoricalNews => Some(1),
        IncomingMessages::HistoricalNewsEnd => Some(1),
        IncomingMessages::HistoricalSchedule => Some(1),
        IncomingMessages::HistoricalTick => Some(1),
        IncomingMessages::HistoricalTickBidAsk => Some(1),
        IncomingMessages::HistoricalTickLast => Some(1),
        IncomingMessages::MarketDepth => Some(2),
        IncomingMessages::MarketDepthL2 => Some(2),
        IncomingMessages::NewsArticle => Some(1),
        IncomingMessages::OpenOrder => Some(1),
        IncomingMessages::PnL => Some(1),
        IncomingMessages::PnLSingle => Some(1),
        IncomingMessages::PositionMulti => Some(2),
        IncomingMessages::PositionMultiEnd => Some(2),
        IncomingMessages::RealTimeBars => Some(2),
        IncomingMessages::ScannerData => Some(2),
        IncomingMessages::SecurityDefinitionOptionParameter => Some(1),
        IncomingMessages::SecurityDefinitionOptionParameterEnd => Some(1),
        IncomingMessages::SymbolSamples => Some(1),
        IncomingMessages::TickByTick => Some(1),
        IncomingMessages::TickEFP => Some(2),
        IncomingMessages::TickGeneric => Some(2),
        IncomingMessages::TickNews => Some(1),
        IncomingMessages::TickOptionComputation => Some(1),
        IncomingMessages::TickPrice => Some(2),
        IncomingMessages::TickReqParams => Some(1),
        IncomingMessages::TickSize => Some(2),
        IncomingMessages::TickSnapshotEnd => Some(2),
        IncomingMessages::TickString => Some(2),
        IncomingMessages::WshEventData => Some(1),
        IncomingMessages::WshMetaData => Some(1),
        IncomingMessages::DisplayGroupList => Some(2),
        IncomingMessages::DisplayGroupUpdated => Some(2),

        _ => {
            debug!("could not determine request id index for {kind:?} (this message type may not have a request id).");
            None
        }
    }
}

/// Outgoing message opcodes understood by TWS/Gateway.
#[allow(dead_code)]
#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
pub enum OutgoingMessages {
    /// Request streaming market data.
    RequestMarketData = 1,
    /// Cancel streaming market data.
    CancelMarketData = 2,
    /// Submit a new order.
    PlaceOrder = 3,
    /// Cancel an existing order.
    CancelOrder = 4,
    /// Request the current open orders.
    RequestOpenOrders = 5,
    /// Request account value updates.
    RequestAccountData = 6,
    /// Request execution reports.
    RequestExecutions = 7,
    /// Request a block of valid order ids.
    RequestIds = 8,
    /// Request contract details.
    RequestContractData = 9,
    /// Request level-two market depth.
    RequestMarketDepth = 10,
    /// Cancel level-two market depth.
    CancelMarketDepth = 11,
    /// Subscribe to news bulletins.
    RequestNewsBulletins = 12,
    /// Cancel news bulletin subscription.
    CancelNewsBulletin = 13,
    /// Change the server log level.
    ChangeServerLog = 14,
    /// Request auto-open orders.
    RequestAutoOpenOrders = 15,
    /// Request all open orders.
    RequestAllOpenOrders = 16,
    /// Request managed accounts list.
    RequestManagedAccounts = 17,
    /// Request financial advisor configuration.
    RequestFA = 18,
    /// Replace financial advisor configuration.
    ReplaceFA = 19,
    /// Request historical bar data.
    RequestHistoricalData = 20,
    /// Exercise an option contract.
    ExerciseOptions = 21,
    /// Subscribe to a market scanner.
    RequestScannerSubscription = 22,
    /// Cancel a market scanner subscription.
    CancelScannerSubscription = 23,
    /// Request scanner parameter definitions.
    RequestScannerParameters = 24,
    /// Cancel an in-flight historical data request.
    CancelHistoricalData = 25,
    /// Request the current TWS/Gateway time.
    RequestCurrentTime = 49,
    /// Request real-time bars.
    RequestRealTimeBars = 50,
    /// Cancel real-time bars.
    CancelRealTimeBars = 51,
    /// Request fundamental data.
    RequestFundamentalData = 52,
    /// Cancel fundamental data.
    CancelFundamentalData = 53,
    /// Request implied volatility calculation.
    ReqCalcImpliedVolat = 54,
    /// Request option price calculation.
    ReqCalcOptionPrice = 55,
    /// Cancel implied volatility calculation.
    CancelImpliedVolatility = 56,
    /// Cancel option price calculation.
    CancelOptionPrice = 57,
    /// Issue a global cancel request.
    RequestGlobalCancel = 58,
    /// Change the active market data type.
    RequestMarketDataType = 59,
    /// Subscribe to position updates.
    RequestPositions = 61,
    /// Subscribe to account summary.
    RequestAccountSummary = 62,
    /// Cancel account summary subscription.
    CancelAccountSummary = 63,
    /// Cancel position subscription.
    CancelPositions = 64,
    /// Begin API verification handshake.
    VerifyRequest = 65,
    /// Respond to verification handshake.
    VerifyMessage = 66,
    /// Query display groups.
    QueryDisplayGroups = 67,
    /// Subscribe to display group events.
    SubscribeToGroupEvents = 68,
    /// Update a display group subscription.
    UpdateDisplayGroup = 69,
    /// Unsubscribe from display group events.
    UnsubscribeFromGroupEvents = 70,
    /// Start the API session.
    StartApi = 71,
    /// Verification handshake with auth.
    VerifyAndAuthRequest = 72,
    /// Verification message with auth.
    VerifyAndAuthMessage = 73,
    /// Request multi-account/model positions.
    RequestPositionsMulti = 74,
    /// Cancel multi-account/model positions.
    CancelPositionsMulti = 75,
    /// Request multi-account/model updates.
    RequestAccountUpdatesMulti = 76,
    /// Cancel multi-account/model updates.
    CancelAccountUpdatesMulti = 77,
    /// Request option security definition parameters.
    RequestSecurityDefinitionOptionalParameters = 78,
    /// Request soft-dollar tier definitions.
    RequestSoftDollarTiers = 79,
    /// Request family codes.
    RequestFamilyCodes = 80,
    /// Request matching symbols.
    RequestMatchingSymbols = 81,
    /// Request exchanges that support depth.
    RequestMktDepthExchanges = 82,
    /// Request smart routing component map.
    RequestSmartComponents = 83,
    /// Request detailed news article.
    RequestNewsArticle = 84,
    /// Request available news providers.
    RequestNewsProviders = 85,
    /// Request historical news headlines.
    RequestHistoricalNews = 86,
    /// Request earliest timestamp for historical data.
    RequestHeadTimestamp = 87,
    /// Request histogram snapshot.
    RequestHistogramData = 88,
    /// Cancel histogram snapshot.
    CancelHistogramData = 89,
    /// Cancel head timestamp request.
    CancelHeadTimestamp = 90,
    /// Request market rule definition.
    RequestMarketRule = 91,
    /// Request account-wide PnL stream.
    RequestPnL = 92,
    /// Cancel account-wide PnL stream.
    CancelPnL = 93,
    /// Request single-position PnL stream.
    RequestPnLSingle = 94,
    /// Cancel single-position PnL stream.
    CancelPnLSingle = 95,
    /// Request historical tick data.
    RequestHistoricalTicks = 96,
    /// Request tick-by-tick data.
    RequestTickByTickData = 97,
    /// Cancel tick-by-tick data.
    CancelTickByTickData = 98,
    /// Request completed order history.
    RequestCompletedOrders = 99,
    /// Request Wall Street Horizon metadata.
    RequestWshMetaData = 100,
    /// Cancel Wall Street Horizon metadata.
    CancelWshMetaData = 101,
    /// Request Wall Street Horizon event data.
    RequestWshEventData = 102,
    /// Cancel Wall Street Horizon event data.
    CancelWshEventData = 103,
    /// Request user information.
    RequestUserInfo = 104,
    /// Request current time in milliseconds.
    RequestCurrentTimeInMillis = 105,
    /// Cancel contract data request.
    CancelContractData = 106,
    /// Cancel historical ticks request.
    CancelHistoricalTicks = 107,
    /// Request configuration.
    ReqConfig = 108,
    /// Update configuration.
    UpdateConfig = 109,
}

impl ToField for OutgoingMessages {
    fn to_field(&self) -> String {
        (*self as i32).to_string()
    }
}

impl std::fmt::Display for OutgoingMessages {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", *self as i32)
    }
}

impl FromStr for OutgoingMessages {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.parse::<i32>() {
            Ok(1) => Ok(OutgoingMessages::RequestMarketData),
            Ok(2) => Ok(OutgoingMessages::CancelMarketData),
            Ok(3) => Ok(OutgoingMessages::PlaceOrder),
            Ok(4) => Ok(OutgoingMessages::CancelOrder),
            Ok(5) => Ok(OutgoingMessages::RequestOpenOrders),
            Ok(6) => Ok(OutgoingMessages::RequestAccountData),
            Ok(7) => Ok(OutgoingMessages::RequestExecutions),
            Ok(8) => Ok(OutgoingMessages::RequestIds),
            Ok(9) => Ok(OutgoingMessages::RequestContractData),
            Ok(10) => Ok(OutgoingMessages::RequestMarketDepth),
            Ok(11) => Ok(OutgoingMessages::CancelMarketDepth),
            Ok(12) => Ok(OutgoingMessages::RequestNewsBulletins),
            Ok(13) => Ok(OutgoingMessages::CancelNewsBulletin),
            Ok(14) => Ok(OutgoingMessages::ChangeServerLog),
            Ok(15) => Ok(OutgoingMessages::RequestAutoOpenOrders),
            Ok(16) => Ok(OutgoingMessages::RequestAllOpenOrders),
            Ok(17) => Ok(OutgoingMessages::RequestManagedAccounts),
            Ok(18) => Ok(OutgoingMessages::RequestFA),
            Ok(19) => Ok(OutgoingMessages::ReplaceFA),
            Ok(20) => Ok(OutgoingMessages::RequestHistoricalData),
            Ok(21) => Ok(OutgoingMessages::ExerciseOptions),
            Ok(22) => Ok(OutgoingMessages::RequestScannerSubscription),
            Ok(23) => Ok(OutgoingMessages::CancelScannerSubscription),
            Ok(24) => Ok(OutgoingMessages::RequestScannerParameters),
            Ok(25) => Ok(OutgoingMessages::CancelHistoricalData),
            Ok(49) => Ok(OutgoingMessages::RequestCurrentTime),
            Ok(50) => Ok(OutgoingMessages::RequestRealTimeBars),
            Ok(51) => Ok(OutgoingMessages::CancelRealTimeBars),
            Ok(52) => Ok(OutgoingMessages::RequestFundamentalData),
            Ok(53) => Ok(OutgoingMessages::CancelFundamentalData),
            Ok(54) => Ok(OutgoingMessages::ReqCalcImpliedVolat),
            Ok(55) => Ok(OutgoingMessages::ReqCalcOptionPrice),
            Ok(56) => Ok(OutgoingMessages::CancelImpliedVolatility),
            Ok(57) => Ok(OutgoingMessages::CancelOptionPrice),
            Ok(58) => Ok(OutgoingMessages::RequestGlobalCancel),
            Ok(59) => Ok(OutgoingMessages::RequestMarketDataType),
            Ok(61) => Ok(OutgoingMessages::RequestPositions),
            Ok(62) => Ok(OutgoingMessages::RequestAccountSummary),
            Ok(63) => Ok(OutgoingMessages::CancelAccountSummary),
            Ok(64) => Ok(OutgoingMessages::CancelPositions),
            Ok(65) => Ok(OutgoingMessages::VerifyRequest),
            Ok(66) => Ok(OutgoingMessages::VerifyMessage),
            Ok(67) => Ok(OutgoingMessages::QueryDisplayGroups),
            Ok(68) => Ok(OutgoingMessages::SubscribeToGroupEvents),
            Ok(69) => Ok(OutgoingMessages::UpdateDisplayGroup),
            Ok(70) => Ok(OutgoingMessages::UnsubscribeFromGroupEvents),
            Ok(71) => Ok(OutgoingMessages::StartApi),
            Ok(72) => Ok(OutgoingMessages::VerifyAndAuthRequest),
            Ok(73) => Ok(OutgoingMessages::VerifyAndAuthMessage),
            Ok(74) => Ok(OutgoingMessages::RequestPositionsMulti),
            Ok(75) => Ok(OutgoingMessages::CancelPositionsMulti),
            Ok(76) => Ok(OutgoingMessages::RequestAccountUpdatesMulti),
            Ok(77) => Ok(OutgoingMessages::CancelAccountUpdatesMulti),
            Ok(78) => Ok(OutgoingMessages::RequestSecurityDefinitionOptionalParameters),
            Ok(79) => Ok(OutgoingMessages::RequestSoftDollarTiers),
            Ok(80) => Ok(OutgoingMessages::RequestFamilyCodes),
            Ok(81) => Ok(OutgoingMessages::RequestMatchingSymbols),
            Ok(82) => Ok(OutgoingMessages::RequestMktDepthExchanges),
            Ok(83) => Ok(OutgoingMessages::RequestSmartComponents),
            Ok(84) => Ok(OutgoingMessages::RequestNewsArticle),
            Ok(85) => Ok(OutgoingMessages::RequestNewsProviders),
            Ok(86) => Ok(OutgoingMessages::RequestHistoricalNews),
            Ok(87) => Ok(OutgoingMessages::RequestHeadTimestamp),
            Ok(88) => Ok(OutgoingMessages::RequestHistogramData),
            Ok(89) => Ok(OutgoingMessages::CancelHistogramData),
            Ok(90) => Ok(OutgoingMessages::CancelHeadTimestamp),
            Ok(91) => Ok(OutgoingMessages::RequestMarketRule),
            Ok(92) => Ok(OutgoingMessages::RequestPnL),
            Ok(93) => Ok(OutgoingMessages::CancelPnL),
            Ok(94) => Ok(OutgoingMessages::RequestPnLSingle),
            Ok(95) => Ok(OutgoingMessages::CancelPnLSingle),
            Ok(96) => Ok(OutgoingMessages::RequestHistoricalTicks),
            Ok(97) => Ok(OutgoingMessages::RequestTickByTickData),
            Ok(98) => Ok(OutgoingMessages::CancelTickByTickData),
            Ok(99) => Ok(OutgoingMessages::RequestCompletedOrders),
            Ok(100) => Ok(OutgoingMessages::RequestWshMetaData),
            Ok(101) => Ok(OutgoingMessages::CancelWshMetaData),
            Ok(102) => Ok(OutgoingMessages::RequestWshEventData),
            Ok(103) => Ok(OutgoingMessages::CancelWshEventData),
            Ok(104) => Ok(OutgoingMessages::RequestUserInfo),
            Ok(105) => Ok(OutgoingMessages::RequestCurrentTimeInMillis),
            Ok(106) => Ok(OutgoingMessages::CancelContractData),
            Ok(107) => Ok(OutgoingMessages::CancelHistoricalTicks),
            Ok(108) => Ok(OutgoingMessages::ReqConfig),
            Ok(109) => Ok(OutgoingMessages::UpdateConfig),
            Ok(n) => Err(Error::Simple(format!("Unknown outgoing message type: {}", n))),
            Err(_) => Err(Error::Simple(format!("Invalid outgoing message type: {}", s))),
        }
    }
}

/// Encode the outbound message length prefix using the IB wire format.
pub fn encode_length(message: &str) -> Vec<u8> {
    let data = message.as_bytes();

    let mut packet: Vec<u8> = Vec::with_capacity(data.len() + 4);

    packet.write_u32::<BigEndian>(data.len() as u32).unwrap();
    packet.write_all(data).unwrap();
    packet
}

/// Builder for outbound TWS/Gateway request messages.
#[derive(Default, Debug, Clone)]
pub struct RequestMessage {
    pub(crate) fields: Vec<String>,
}

impl RequestMessage {
    /// Create a new empty request message.
    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn push_field<T: ToField>(&mut self, val: &T) -> &RequestMessage {
        let field = val.to_field();
        self.fields.push(field);
        self
    }

    /// Serialize all fields into the NUL-delimited wire format.
    pub fn encode(&self) -> String {
        let mut data = self.fields.join("\0");
        data.push('\0');
        data
    }

    #[cfg(test)]
    pub(crate) fn len(&self) -> usize {
        self.fields.len()
    }

    #[cfg(test)]
    /// Serialize the message as a pipe-delimited string (test helper).
    pub(crate) fn encode_simple(&self) -> String {
        let mut data = self.fields.join("|");
        data.push('|');
        data
    }
    #[cfg(test)]
    /// Construct a request message from a NUL-delimited string (test helper).
    pub fn from(fields: &str) -> RequestMessage {
        RequestMessage {
            fields: fields.split_terminator('\x00').map(|x| x.to_string()).collect(),
        }
    }
    #[cfg(test)]
    /// Construct a request message from a pipe-delimited string (test helper).
    pub fn from_simple(fields: &str) -> RequestMessage {
        RequestMessage {
            fields: fields.split_terminator('|').map(|x| x.to_string()).collect(),
        }
    }
}

impl Index<usize> for RequestMessage {
    type Output = String;

    fn index(&self, i: usize) -> &Self::Output {
        &self.fields[i]
    }
}

/// Parsed inbound message from TWS/Gateway.
#[derive(Clone, Default, Debug)]
pub struct ResponseMessage {
    /// Cursor index for incremental decoding.
    pub i: usize,
    /// Raw field buffer backing this message.
    pub fields: Vec<String>,
    /// Server version for version-gated decoding (e.g. error message format).
    pub server_version: i32,
}

impl ResponseMessage {
    /// Number of fields present in the message.
    pub fn len(&self) -> usize {
        self.fields.len()
    }

    /// Returns `true` if the message contains no fields.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }

    /// Returns `true` if the message informs about API shutdown.
    pub fn is_shutdown(&self) -> bool {
        self.message_type() == IncomingMessages::Shutdown
    }

    /// Return the discriminator identifying the message payload.
    pub fn message_type(&self) -> IncomingMessages {
        if self.fields.is_empty() {
            IncomingMessages::NotValid
        } else {
            let message_id = i32::from_str(&self.fields[0]).unwrap_or(-1);
            IncomingMessages::from(message_id)
        }
    }

    /// Try to extract the request id from the message.
    pub fn request_id(&self) -> Option<i32> {
        if let Some(i) = request_id_index(self.message_type()) {
            if let Ok(request_id) = self.peek_int(i) {
                return Some(request_id);
            }
        }
        None
    }

    /// Try to extract the order id from the message.
    pub fn order_id(&self) -> Option<i32> {
        if let Some(i) = order_id_index(self.message_type()) {
            if let Ok(order_id) = self.peek_int(i) {
                return Some(order_id);
            }
        }
        None
    }

    /// Try to extract the execution id from the message.
    pub fn execution_id(&self) -> Option<String> {
        match self.message_type() {
            IncomingMessages::ExecutionData => Some(self.peek_string(14)),
            IncomingMessages::CommissionsReport => Some(self.peek_string(2)),
            _ => None,
        }
    }

    /// Peek an integer field without advancing the cursor.
    pub fn peek_int(&self, i: usize) -> Result<i32, Error> {
        if i >= self.fields.len() {
            return Err(Error::Simple("expected int and found end of message".into()));
        }

        let field = &self.fields[i];
        match field.parse() {
            Ok(val) => Ok(val),
            Err(err) => Err(Error::Parse(i, field.into(), err.to_string())),
        }
    }

    /// Peek a long field without advancing the cursor.
    pub fn peek_long(&self, i: usize) -> Result<i64, Error> {
        if i >= self.fields.len() {
            return Err(Error::Simple("expected long and found end of message".into()));
        }

        let field = &self.fields[i];
        match field.parse() {
            Ok(val) => Ok(val),
            Err(err) => Err(Error::Parse(i, field.into(), err.to_string())),
        }
    }

    /// Peek a string field without advancing the cursor.
    pub fn peek_string(&self, i: usize) -> String {
        self.fields[i].to_owned()
    }

    /// Consume and parse the next integer field.
    pub fn next_int(&mut self) -> Result<i32, Error> {
        if self.i >= self.fields.len() {
            return Err(Error::Simple("expected int and found end of message".into()));
        }

        let field = &self.fields[self.i];
        self.i += 1;

        match field.parse() {
            Ok(val) => Ok(val),
            Err(err) => Err(Error::Parse(self.i, field.into(), err.to_string())),
        }
    }

    /// Consume the next field returning `None` when unset.
    pub fn next_optional_int(&mut self) -> Result<Option<i32>, Error> {
        if self.i >= self.fields.len() {
            return Err(Error::Simple("expected optional int and found end of message".into()));
        }

        let field = &self.fields[self.i];
        self.i += 1;

        if field.is_empty() || field == UNSET_INTEGER {
            return Ok(None);
        }

        match field.parse::<i32>() {
            Ok(val) => Ok(Some(val)),
            Err(err) => Err(Error::Parse(self.i, field.into(), err.to_string())),
        }
    }

    /// Consume the next field as a boolean (`"0"` or `"1"`).
    pub fn next_bool(&mut self) -> Result<bool, Error> {
        if self.i >= self.fields.len() {
            return Err(Error::Simple("expected bool and found end of message".into()));
        }

        let field = &self.fields[self.i];
        self.i += 1;

        Ok(field == "1")
    }

    /// Consume and parse the next i64 field.
    pub fn next_long(&mut self) -> Result<i64, Error> {
        if self.i >= self.fields.len() {
            return Err(Error::Simple("expected long and found end of message".into()));
        }

        let field = &self.fields[self.i];
        self.i += 1;

        match field.parse() {
            Ok(val) => Ok(val),
            Err(err) => Err(Error::Parse(self.i, field.into(), err.to_string())),
        }
    }

    /// Consume the next field as an optional i64.
    pub fn next_optional_long(&mut self) -> Result<Option<i64>, Error> {
        if self.i >= self.fields.len() {
            return Err(Error::Simple("expected optional long and found end of message".into()));
        }

        let field = &self.fields[self.i];
        self.i += 1;

        if field.is_empty() || field == UNSET_LONG {
            return Ok(None);
        }

        match field.parse::<i64>() {
            Ok(val) => Ok(Some(val)),
            Err(err) => Err(Error::Parse(self.i, field.into(), err.to_string())),
        }
    }

    /// Consume the next field and parse it as an IB timestamp.
    pub fn next_date_time(&mut self) -> Result<OffsetDateTime, Error> {
        self.next_date_time_with_timezone(None)
    }

    /// Consume the next field and parse it as a timestamp using an optional session timezone.
    pub fn next_date_time_with_timezone(&mut self, time_zone: Option<&Tz>) -> Result<OffsetDateTime, Error> {
        if self.i >= self.fields.len() {
            return Err(Error::Simple("expected datetime and found end of message".into()));
        }

        let field = &self.fields[self.i];
        self.i += 1;

        if field.is_empty() {
            return Err(Error::Simple("expected timestamp and found empty string".into()));
        }

        parse_ib_date_time_with_timezone(field, time_zone).map_err(|err| match err {
            Error::Parse(_, _, _) | Error::Simple(_) => Error::Parse(self.i, field.into(), err.to_string()),
            other => other,
        })
    }

    /// Consume the next field as a string.
    pub fn next_string(&mut self) -> Result<String, Error> {
        if self.i >= self.fields.len() {
            return Err(Error::Simple("expected string and found end of message".into()));
        }

        let field = &self.fields[self.i];
        self.i += 1;
        Ok(String::from(field))
    }

    /// Consume and parse the next floating-point field.
    pub fn next_double(&mut self) -> Result<f64, Error> {
        if self.i >= self.fields.len() {
            return Err(Error::Simple("expected double and found end of message".into()));
        }

        let field = &self.fields[self.i];
        self.i += 1;

        if field.is_empty() || field == "0" || field == "0.0" {
            return Ok(0.0);
        }

        match field.parse() {
            Ok(val) => Ok(val),
            Err(err) => Err(Error::Parse(self.i, field.into(), err.to_string())),
        }
    }

    /// Consume the next field as an optional floating-point value.
    pub fn next_optional_double(&mut self) -> Result<Option<f64>, Error> {
        if self.i >= self.fields.len() {
            return Err(Error::Simple("expected optional double and found end of message".into()));
        }

        let field = &self.fields[self.i];
        self.i += 1;

        if field.is_empty() || field == UNSET_DOUBLE {
            return Ok(None);
        }

        if field == INFINITY_STR {
            return Ok(Some(f64::INFINITY));
        }

        match field.parse() {
            Ok(val) => Ok(Some(val)),
            Err(err) => Err(Error::Parse(self.i, field.into(), err.to_string())),
        }
    }

    /// Offset applied to error field indices based on server version.
    /// New format (>= ERROR_TIME) drops the version field, shifting indices by -1.
    fn error_field_offset(&self) -> usize {
        if self.server_version >= crate::server_versions::ERROR_TIME {
            0
        } else {
            1
        }
    }

    /// Field index of the request ID in an error message.
    pub fn error_request_id_index(&self) -> usize {
        1 + self.error_field_offset()
    }

    /// Field index of the error code in an error message.
    pub fn error_code_index(&self) -> usize {
        2 + self.error_field_offset()
    }

    /// Field index of the error message text in an error message.
    pub fn error_message_index(&self) -> usize {
        3 + self.error_field_offset()
    }

    /// Extract the request ID from an error message.
    pub fn error_request_id(&self) -> i32 {
        self.peek_int(self.error_request_id_index()).unwrap_or(-1)
    }

    /// Extract the error code from an error message.
    pub fn error_code(&self) -> i32 {
        self.peek_int(self.error_code_index()).unwrap_or(0)
    }

    /// Extract the error message text from an error message.
    pub fn error_message(&self) -> String {
        let idx = self.error_message_index();
        if idx < self.fields.len() {
            self.peek_string(idx)
        } else {
            String::from("Unknown error")
        }
    }

    /// Extract the error timestamp from an error message.
    /// Only present for server versions >= ERROR_TIME.
    pub fn error_time(&self) -> Option<OffsetDateTime> {
        if self.server_version >= crate::server_versions::ERROR_TIME {
            // New format: msg_type, request_id, error_code, error_msg, advanced_order_reject_json, error_time
            let idx = self.error_message_index() + 2;
            let millis = self.peek_long(idx).ok()?;
            OffsetDateTime::from_unix_timestamp_nanos(millis as i128 * 1_000_000).ok()
        } else {
            None
        }
    }

    /// Build a response message from a NUL-delimited payload.
    pub fn from(fields: &str) -> ResponseMessage {
        ResponseMessage {
            i: 0,
            fields: fields.split_terminator('\x00').map(|x| x.to_string()).collect(),
            server_version: 0,
        }
    }
    #[cfg(test)]
    /// Build a response message from a pipe-delimited payload (test helper).
    pub fn from_simple(fields: &str) -> ResponseMessage {
        ResponseMessage {
            i: 0,
            fields: fields.split_terminator('|').map(|x| x.to_string()).collect(),
            server_version: 0,
        }
    }

    /// Set the server version for version-gated decoding (builder style).
    pub fn with_server_version(mut self, server_version: i32) -> Self {
        self.server_version = server_version;
        self
    }

    /// Advance the cursor past the next field.
    pub fn skip(&mut self) {
        self.i += 1;
    }

    /// Encode the message back into a NUL-delimited string.
    pub fn encode(&self) -> String {
        let mut data = self.fields.join("\0");
        data.push('\0');
        data
    }

    #[cfg(test)]
    /// Serialize the message into a pipe-delimited format (test helper).
    pub fn encode_simple(&self) -> String {
        let mut data = self.fields.join("|");
        data.push('|');
        data
    }
}

pub(crate) fn parse_ib_date_time_with_timezone(field: &str, time_zone: Option<&Tz>) -> Result<OffsetDateTime, Error> {
    let utc_format = format_description!("[year][month][day]-[hour]:[minute]:[second]");
    if let Ok(dt) = PrimitiveDateTime::parse(field, utc_format) {
        return Ok(dt.assume_utc());
    }

    let tz_format = format_description!("[year][month][day] [hour]:[minute]:[second]");
    if let Some((datetime_part, tz_name)) = field.rsplit_once(' ') {
        if let Ok(dt) = PrimitiveDateTime::parse(datetime_part, tz_format) {
            let zones = find_timezone(tz_name.trim());
            if let Some(tz) = zones.first().copied() {
                return resolve_primitive_date_time(field, dt, tz);
            }
            return Err(Error::Simple(format!("unrecognized timezone in IB datetime field: {field}")));
        }
    }

    if let Some(tz) = time_zone {
        // IB uses double-space between date and time for session-local timestamps
        let naive_format = format_description!("[year][month][day]  [hour]:[minute]:[second]");
        if let Ok(dt) = PrimitiveDateTime::parse(field, naive_format) {
            return resolve_primitive_date_time(field, dt, tz);
        }

        if field.len() == 8 {
            let date_format = format_description!("[year][month][day]");
            if let Ok(date) = Date::parse(field, date_format) {
                return resolve_primitive_date_time(field, date.midnight(), tz);
            }
        }
    }

    if let Ok(timestamp) = field.parse::<i64>() {
        return OffsetDateTime::from_unix_timestamp(timestamp).map_err(|err| Error::Simple(err.to_string()));
    }

    Err(Error::Simple(format!("failed to parse IB datetime field: {field}")))
}

fn resolve_primitive_date_time(field: &str, date_time: PrimitiveDateTime, time_zone: &Tz) -> Result<OffsetDateTime, Error> {
    match date_time.assume_timezone(time_zone) {
        OffsetResult::Some(value) => Ok(value),
        OffsetResult::Ambiguous(_, _) => Err(Error::Simple(format!(
            "ambiguous IB datetime field in timezone {}: {field}",
            time_zone.name(),
        ))),
        OffsetResult::None => Err(Error::Simple(format!(
            "invalid IB datetime field in timezone {}: {field}",
            time_zone.name(),
        ))),
    }
}

/// An error message from the TWS API.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Notice {
    /// Error code reported by TWS.
    pub code: i32,
    /// Human-readable error message text.
    pub message: String,
    /// Timestamp when the error occurred.
    /// Only present for server versions >= ERROR_TIME (194).
    pub error_time: Option<OffsetDateTime>,
}

/// Error code indicating an order was cancelled (confirmation, not an error).
pub const ORDER_CANCELLED_CODE: i32 = 202;

/// Range of error codes that are considered warnings (2100-2169).
pub const WARNING_CODE_RANGE: std::ops::RangeInclusive<i32> = 2100..=2169;

/// System message codes indicating connectivity status.
/// - 1100: Connectivity lost
/// - 1101: Connectivity restored, market data lost (resubscribe needed)
/// - 1102: Connectivity restored, market data maintained
/// - 1300: Socket port reset during active connection
pub const SYSTEM_MESSAGE_CODES: [i32; 4] = [1100, 1101, 1102, 1300];

impl Notice {
    #[allow(private_interfaces)]
    /// Construct a notice from a response message.
    pub fn from(message: &ResponseMessage) -> Notice {
        let code = message.error_code();
        let error_time = message.error_time();
        let message = message.error_message();
        Notice { code, message, error_time }
    }

    /// Returns `true` if this notice indicates an order was cancelled (code 202).
    ///
    /// Code 202 is sent by TWS to confirm an order cancellation. This is an
    /// informational message, not an error.
    pub fn is_cancellation(&self) -> bool {
        self.code == ORDER_CANCELLED_CODE
    }

    /// Returns `true` if this is a warning message (codes 2100-2169).
    pub fn is_warning(&self) -> bool {
        WARNING_CODE_RANGE.contains(&self.code)
    }

    /// Returns `true` if this is a system/connectivity message (codes 1100-1102, 1300).
    ///
    /// System messages indicate connectivity status changes:
    /// - 1100: Connectivity between IB and TWS lost
    /// - 1101: Connectivity restored, market data lost (resubscribe needed)
    /// - 1102: Connectivity restored, market data maintained
    /// - 1300: Socket port reset during active connection
    pub fn is_system_message(&self) -> bool {
        SYSTEM_MESSAGE_CODES.contains(&self.code)
    }

    /// Returns `true` if this is an informational notice (not an error).
    ///
    /// Informational notices include cancellation confirmations, warnings,
    /// and system/connectivity messages.
    pub fn is_informational(&self) -> bool {
        self.is_cancellation() || self.is_warning() || self.is_system_message()
    }

    /// Returns `true` if this is an error requiring attention.
    ///
    /// Returns `false` for informational messages like cancellation confirmations,
    /// warnings, and system messages.
    pub fn is_error(&self) -> bool {
        !self.is_informational()
    }
}

impl Display for Notice {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] {}", self.code, self.message)
    }
}