rustrade-instrument 0.16.0

Core Rustrade Exchange, Instrument and Asset data structures and associated utilities.
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
use crate::{
    Keyed,
    asset::{Asset, AssetIndex, ExchangeAsset},
    exchange::{ExchangeId, ExchangeIndex},
    index::{
        IndexedInstruments, error::IndexError, find_asset_by_exchange_and_name_internal,
        find_exchange_by_exchange_id,
    },
    instrument::{Instrument, InstrumentIndex, spec::OrderQuantityUnits},
};
use rust_decimal::Decimal;
use smol_str::StrExt;
use std::collections::HashMap;

#[derive(Debug, Default)]
pub struct IndexedInstrumentsBuilder {
    exchanges: Vec<ExchangeId>,
    instruments: Vec<Instrument<ExchangeId, Asset>>,
    assets: Vec<ExchangeAsset<Asset>>,
}

impl IndexedInstrumentsBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers an [`Instrument`], together with the exchanges and assets it implies.
    ///
    /// Nothing is validated here — duplicates are tolerated and de-duplicated, and every invariant
    /// (unique `name_internal`, positive contract multipliers, resolvable asset references) is
    /// enforced by [`Self::try_build`].
    ///
    /// # What a `data_venue` registers, and what it deliberately does not
    /// An instrument carrying a [`DataVenue`](crate::instrument::data_venue::DataVenue) registers
    /// **two** exchanges — the one it executes on and the one it is priced on. So
    /// [`IndexedInstruments::exchanges`] is wider than the set of `Instrument::exchange` values, and
    /// a data-only venue receives the [`ExchangeIndex`] it needs in order to carry connectivity
    /// state; without one, the first market event from that venue has no state to resolve.
    ///
    /// Its **assets are not registered**. Every asset an instrument implies — underlying base and
    /// quote, settlement asset, and any `OrderQuantityUnits::Asset` — is registered against the
    /// *execution* venue alone, so a data-only venue contributes zero entries to
    /// [`IndexedInstruments::assets`]. An [`ExchangeAsset`] keys balance state, and a venue that
    /// only publishes prices holds no balance to key.
    ///
    /// That asymmetry is load bearing in both directions, and worth knowing before relying on
    /// either half:
    /// - It is why a data-only venue seeds no phantom balances it could never report, and why the
    ///   asset index space is not doubled for every dual-venue instrument.
    /// - It is also why any lookup that reaches an instrument *through* its assets cannot honour a
    ///   data venue. `index_market_data_subscription_batches` is the one in tree: asked for a data
    ///   venue it fails with an asset-index error, and asked for the execution venue it succeeds
    ///   with the correct instrument index against the wrong feed.
    pub fn add_instrument(mut self, instrument: Instrument<ExchangeId, Asset>) -> Self {
        // Add ExchangeId
        self.exchanges.push(instrument.exchange);

        // Add the market-data venue, when the instrument is priced somewhere other than where it
        // is executed. Registering it is what gives a data-only venue an `ExchangeIndex`, and
        // therefore an entry in `ConnectivityStates` -- without which the first market event from
        // that venue hits a missing-exchange lookup.
        //
        // Its ASSETS are deliberately NOT registered. An `ExchangeAsset` keys balance state
        // (`generate_empty_indexed_asset_states`), and a data-only venue holds no balances: it
        // publishes prices and has no account. Registering them would seed phantom balances for a
        // venue that can never report one, and double the asset index space for every dual-venue
        // instrument. The instrument's own asset keys resolve against its execution venue, which
        // is where its balances actually live.
        if let Some(data_venue) = &instrument.data_venue {
            self.exchanges.push(data_venue.exchange);
        }

        // Add Underlying base
        self.assets.push(ExchangeAsset::new(
            instrument.exchange,
            instrument.underlying.base.clone(),
        ));

        // Add Underlying quote
        self.assets.push(ExchangeAsset::new(
            instrument.exchange,
            instrument.underlying.quote.clone(),
        ));

        // Add the settlement asset for every kind that has one (all but Spot)
        if let Some(settlement_asset) = instrument.kind.settlement_asset() {
            self.assets.push(ExchangeAsset::new(
                instrument.exchange,
                settlement_asset.clone(),
            ));
        }

        // Add Instrument OrderQuantityUnits if it's defined in asset units
        // --> likely a duplicate asset, but if so will be filtered during Self::build()
        if let Some(spec) = instrument.spec.as_ref()
            && let OrderQuantityUnits::Asset(asset) = &spec.quantity.unit
        {
            self.assets
                .push(ExchangeAsset::new(instrument.exchange, asset.clone()));
        }

        // Add Instrument
        self.instruments.push(instrument);

        self
    }

    /// Registers an asset that no added [`Instrument`] implies, together with its exchange.
    ///
    /// This is for an asset the account holds or pays with but does not trade. An example is
    /// BNB on Binance spot with "pay fees with BNB" turned on: fills report their fee in BNB, and
    /// the account reports a BNB balance. Once it is registered, fees and balances in that asset
    /// index like any other, and the engine keeps a balance for it.
    ///
    /// A fee charged in such an asset is neither the instrument's base nor its quote, so the
    /// execution indexer gives it no quote equivalent (`AssetFees::fees_quote` is `None`). The
    /// `rustrade` engine values the fee when it also has a spot instrument pairing the asset with
    /// the fill's quote, such as `BNBUSDT`, with a price. The asset's balance is not valued.
    ///
    /// Pass the venue that holds the balance, the **execution** venue. An asset registers balance
    /// state on its exchange, so registering one on a data-only venue seeds a balance that venue
    /// can never report (see [`Self::add_instrument`]).
    ///
    /// Assets are validated and indexed by [`Self::try_build`] the same way whichever method added
    /// them:
    /// - An exact duplicate of an asset an instrument implies is removed.
    /// - A name that conflicts with another asset on the same exchange fails the build, such as the
    ///   same `name_internal` with a different `name_exchange`, or an exchange name differing only
    ///   in case.
    /// - [`AssetIndex`] values are assigned after sorting, so registering an asset can change the
    ///   indices of others. Resolve indices from the built [`IndexedInstruments`], never hard-code
    ///   them.
    ///
    /// A balance snapshot or update a venue reports for an asset that is not registered, by this
    /// method or by an instrument, is not tracked: the execution manager drops it, logging the
    /// first one for each asset at `warn!`. Register every asset whose balance matters, such as a
    /// fee asset.
    pub fn add_asset(mut self, asset: ExchangeAsset<Asset>) -> Self {
        self.exchanges.push(asset.exchange);
        self.assets.push(asset);
        self
    }

    /// Builds an [`IndexedInstruments`], panicking if the added [`Instrument`]s are not a valid
    /// collection.
    ///
    /// # Panics
    /// Panics if two added `Instrument`s share an
    /// [`InstrumentNameInternal`](crate::instrument::name::InstrumentNameInternal), if two on one
    /// exchange share an
    /// [`InstrumentNameExchange`](crate::instrument::name::InstrumentNameExchange), if two distinct
    /// assets on one exchange share an
    /// [`AssetNameInternal`](crate::asset::name::AssetNameInternal), or if any added `Instrument`
    /// carries a non-positive `contract_size` — see [`Self::try_build`], which returns each as an
    /// [`IndexError`] instead.
    pub fn build(self) -> IndexedInstruments {
        // Deliberate panic: `build` is the infallible convenience over `try_build`, and every
        // failure it can raise is a caller error that must not be silently tolerated (see
        // `try_build`'s rustdoc). Panics with the error's `Display`, not `expect`'s `Debug`, so
        // the operator reads the offending instrument rather than a quoted struct dump.
        #[allow(clippy::panic)] // Documented in this method's `# Panics` section.
        self.try_build()
            .unwrap_or_else(|error| panic!("failed to build IndexedInstruments: {error}"))
    }

    /// Builds an [`IndexedInstruments`], returning an [`IndexError`] if the added [`Instrument`]s
    /// are not a valid collection.
    ///
    /// # Errors
    /// Returns [`IndexError::DuplicateInstrumentNameInternal`] if two added `Instrument`s share an
    /// [`InstrumentNameInternal`](crate::instrument::name::InstrumentNameInternal),
    /// [`IndexError::DuplicateInstrumentNameExchange`] if two on one exchange share an
    /// [`InstrumentNameExchange`](crate::instrument::name::InstrumentNameExchange) ignoring ASCII
    /// case, [`IndexError::DuplicateAssetNameInternal`] if two distinct assets on one exchange share
    /// an [`AssetNameInternal`](crate::asset::name::AssetNameInternal),
    /// [`IndexError::DuplicateAssetNameExchange`] if two distinct assets on one exchange share an
    /// [`AssetNameExchange`](crate::asset::name::AssetNameExchange) ignoring ASCII case, or
    /// [`IndexError::InvalidContractSize`] if any added `Instrument` carries a non-positive
    /// `contract_size`.
    ///
    /// `InstrumentNameInternal` must be unique across the collection: downstream state maps are
    /// keyed on it while being read **positionally** by [`InstrumentIndex`], so a duplicate
    /// collapses two instruments into one map entry and silently shifts every index past the
    /// collision onto the wrong instrument — attaching positions, PnL and orders to the wrong
    /// place, with no error until the final index panics. Note that the `Instrument` dedup below
    /// does **not** cover this: it removes only instruments that are equal in *every* field, so
    /// two genuinely different instruments that merely share a name survive it.
    ///
    /// `(exchange, name_exchange)` must be unique too: it is how a venue names an instrument, so it
    /// is what every venue-sourced order, fill and position is resolved by. Two instruments
    /// sharing it, such as a spot and a CFD both named `AAPL` on one venue, would leave each of
    /// those lookups to pick one of the two arbitrarily. Register each on the name that venue
    /// distinguishes it by (IBKR's `AAPL` and `AAPL.CFD`, say); two instruments a venue reports
    /// under one name cannot be represented.
    ///
    /// Both exchange-side names are unique **ignoring ASCII case**, for instruments and assets
    /// alike, because the execution lookup that resolves a venue's name ignores case: venues and
    /// clients do not always spell a name the way it was registered (`usd` against `USD`). Two
    /// names that differ only in case are therefore one name, and registering both is rejected
    /// rather than left for a lookup to pick one.
    pub fn try_build(mut self) -> Result<IndexedInstruments, IndexError> {
        // Sort & dedup
        self.exchanges.sort();
        self.exchanges.dedup();
        self.instruments.sort();
        self.instruments.dedup();
        self.assets.sort();
        self.assets.dedup();

        // Enforce that every contract multiplier is positive. Applied through
        // `InstrumentKind::contract_size`, so it covers every kind uniformly -- `Spot` reports a
        // hard `Decimal::ONE` and can never trip it, and carving the contract-bearing kinds out
        // individually would take more code than checking them all. See
        // `IndexError::InvalidContractSize` for why neither degenerate value fails downstream.
        for instrument in &self.instruments {
            let contract_size = instrument.kind.contract_size();
            if contract_size <= Decimal::ZERO {
                return Err(IndexError::InvalidContractSize(format!(
                    "{} ({:?}) on {} carries contract_size {contract_size}, but a contract \
                     multiplier must be positive - it scales notional, PnL and fees, so zero \
                     silently zeroes all three and a negative value inverts the sign of PnL",
                    instrument.name_internal,
                    instrument.kind,
                    // `as_str`, not `Display`: the canonical snake_case spelling users write in
                    // configs, rather than the bare variant name.
                    instrument.exchange.as_str(),
                )));
            }
        }

        // Enforce the InstrumentNameInternal uniqueness invariant that index-keyed state assumes.
        // Checked after the dedup above so exact duplicate `Instrument`s -- which are legitimate
        // input, already collapsed to one -- do not trip it.
        let mut names = HashMap::with_capacity(self.instruments.len());
        for instrument in &self.instruments {
            if let Some(previous) = names.insert(&instrument.name_internal, instrument) {
                // The whole `Instrument` is retained, not just its `name_exchange`, because the two
                // colliding instruments frequently share that name: a spot and a CFD on one symbol
                // is the collision this check most plausibly catches, and reporting it as
                // "AAPL and AAPL" asserts they are distinct while printing nothing that
                // distinguishes them. `describe_collision` is what does.
                let [previous, instrument_desc] = describe_collision(previous, instrument);
                return Err(IndexError::DuplicateInstrumentNameInternal(format!(
                    "{} is shared by the distinct instruments {previous} and {instrument_desc} on \
                     {} - every Instrument requires a unique name_internal",
                    instrument.name_internal,
                    // `as_str`, not `Display`: the canonical snake_case spelling users write in
                    // configs, rather than the bare variant name.
                    instrument.exchange.as_str(),
                )));
            }
        }

        // Enforce `(exchange, name_exchange)` uniqueness, ignoring ASCII case: it is the key every
        // venue-sourced order, fill and position is resolved by, and that lookup ignores case (see
        // `try_build`'s rustdoc). Checked after the `name_internal` pass, so a pair reaching it
        // always differs in `name_internal`.
        let mut exchange_names = HashMap::with_capacity(self.instruments.len());
        for instrument in &self.instruments {
            let key = (
                instrument.exchange,
                instrument.name_exchange.name().to_ascii_lowercase_smolstr(),
            );
            if let Some(previous) = exchange_names.insert(key, instrument) {
                let [previous_desc, instrument_desc] = describe_collision(previous, instrument);
                let name = if previous.name_exchange == instrument.name_exchange {
                    instrument.name_exchange.to_string()
                } else {
                    format!(
                        "{} (as {}, the same name ignoring case)",
                        instrument.name_exchange, previous.name_exchange
                    )
                };
                return Err(IndexError::DuplicateInstrumentNameExchange(format!(
                    "{name} on {} is shared by the distinct instruments {previous_desc} and \
                     {instrument_desc} - every Instrument on an exchange requires a name_exchange \
                     unique ignoring ASCII case, since that is the name the exchange reports it by",
                    // `as_str`, not `Display`: the canonical snake_case spelling users write in
                    // configs, rather than the bare variant name.
                    instrument.exchange.as_str(),
                )));
            }
        }

        // Enforce the asset-side twin: `(exchange, name_internal)` must be unique across assets.
        // The dedup above removes only fully equal assets, so two assets differing only in
        // `name_exchange` survive it, and would take two `AssetIndex` slots that lookups keyed on
        // `name_internal` cannot tell apart.
        let mut asset_names = HashMap::with_capacity(self.assets.len());
        for exchange_asset in &self.assets {
            let key = (exchange_asset.exchange, &exchange_asset.asset.name_internal);
            if let Some(previous) = asset_names.insert(key, exchange_asset) {
                return Err(IndexError::DuplicateAssetNameInternal(format!(
                    "{} on {} is shared by the distinct assets with name_exchange {} and {} - \
                     every asset on an exchange requires a unique name_internal",
                    exchange_asset.asset.name_internal,
                    // `as_str`, not `Display`: the canonical snake_case spelling users write in
                    // configs, rather than the bare variant name.
                    exchange_asset.exchange.as_str(),
                    previous.asset.name_exchange,
                    exchange_asset.asset.name_exchange,
                )));
            }
        }

        // Enforce `(exchange, name_exchange)` uniqueness across assets, ignoring ASCII case: it is
        // the key every venue-sourced balance and fee is resolved by. Checked after the
        // `name_internal` pass, so a pair reaching it always differs in `name_internal`.
        let mut asset_exchange_names = HashMap::with_capacity(self.assets.len());
        for exchange_asset in &self.assets {
            let key = (
                exchange_asset.exchange,
                exchange_asset
                    .asset
                    .name_exchange
                    .name()
                    .to_ascii_lowercase_smolstr(),
            );
            if let Some(previous) = asset_exchange_names.insert(key, exchange_asset) {
                return Err(IndexError::DuplicateAssetNameExchange(format!(
                    "{} and {} on {} name the distinct assets with name_internal {} and {} - \
                     every asset on an exchange requires a name_exchange unique ignoring ASCII \
                     case, since that is the name the exchange reports it by",
                    previous.asset.name_exchange,
                    exchange_asset.asset.name_exchange,
                    // `as_str`, not `Display`: the canonical snake_case spelling users write in
                    // configs, rather than the bare variant name.
                    exchange_asset.exchange.as_str(),
                    previous.asset.name_internal,
                    exchange_asset.asset.name_internal,
                )));
            }
        }

        // Index Exchanges
        let exchanges = self
            .exchanges
            .into_iter()
            .enumerate()
            .map(|(index, exchange)| Keyed::new(ExchangeIndex::new(index), exchange))
            .collect::<Vec<_>>();

        // Index Assets
        let assets = self
            .assets
            .into_iter()
            .enumerate()
            .map(|(index, exchange_asset)| Keyed::new(AssetIndex::new(index), exchange_asset))
            .collect::<Vec<_>>();

        // Index Instruments (also maps any Instrument AssetKeys -> AssetIndex)
        let instruments = self
            .instruments
            .into_iter()
            .enumerate()
            .map(|(index, instrument)| {
                let exchange_id = instrument.exchange;

                // Applied to the execution venue AND to any `DataVenue`, so a data-only venue is
                // indexed on the same terms. Holds because `add_instrument` registers both.
                let instrument = instrument.map_exchange_key(|id| {
                    #[allow(clippy::expect_used)]
                    // Invariant: add_instrument populates exchanges alongside each instrument
                    let exchange_key = find_exchange_by_exchange_id(&exchanges, id)
                        .expect("every exchange related to every instrument has been added");

                    Keyed::new(exchange_key, *id)
                });

                #[allow(clippy::expect_used)]
                // Invariant: add_instrument populates assets alongside each instrument
                let instrument = instrument
                    .map_asset_key_with_lookup(|asset: &Asset| {
                        find_asset_by_exchange_and_name_internal(
                            &assets,
                            exchange_id,
                            &asset.name_internal,
                        )
                    })
                    .expect("every asset related to every instrument has been added");

                Keyed::new(InstrumentIndex::new(index), instrument)
            })
            .collect();

        Ok(IndexedInstruments {
            exchanges,
            instruments,
            assets,
        })
    }
}

/// Renders each of two colliding `Instrument`s as its `name_exchange` followed by every field on
/// which it differs from the other, so that a message naming both says which configured entry is
/// which.
///
/// A fixed subset of fields would not do: the full-equality dedup lets through a pair that differs
/// in any one field, so a pair differing only in, say, `underlying` would read "AAPL and AAPL".
fn describe_collision(
    a: &Instrument<ExchangeId, Asset>,
    b: &Instrument<ExchangeId, Asset>,
) -> [String; 2] {
    let describe = |this: &Instrument<ExchangeId, Asset>, other: &Instrument<ExchangeId, Asset>| {
        let mut differences = Vec::new();
        if this.name_internal != other.name_internal {
            differences.push(format!("name_internal {}", this.name_internal));
        }
        if this.exchange != other.exchange {
            // `as_str`, not `Display`: the canonical snake_case spelling users write in configs,
            // rather than the bare variant name.
            differences.push(format!("on {}", this.exchange.as_str()));
        }
        if this.kind != other.kind {
            differences.push(format!("{:?}", this.kind));
        }
        if this.underlying != other.underlying {
            let pair = |underlying: &crate::Underlying<Asset>| {
                format!(
                    "{}/{}",
                    underlying.base.name_internal, underlying.quote.name_internal
                )
            };
            // The internal names are what a config spells, so they are the readable form; only an
            // underlying differing in its assets' exchange-side names alone needs the full dump.
            differences.push(if pair(&this.underlying) != pair(&other.underlying) {
                format!("underlying {}", pair(&this.underlying))
            } else {
                format!("underlying {:?}", this.underlying)
            });
        }
        if this.quote != other.quote {
            differences.push(format!("quote {:?}", this.quote));
        }
        if this.spec != other.spec {
            differences.push(format!("spec {:?}", this.spec));
        }
        if this.data_venue != other.data_venue {
            differences.push(match &this.data_venue {
                Some(data_venue) => format!(
                    "priced on {} as {}",
                    data_venue.exchange.as_str(),
                    this.data_name_exchange(),
                ),
                None => "priced on its own venue".to_owned(),
            });
        }

        if differences.is_empty() {
            this.name_exchange.to_string()
        } else {
            format!("{} ({})", this.name_exchange, differences.join(", "))
        }
    };

    [describe(a, b), describe(b, a)]
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)] // Test code: panics on bad input are acceptable
mod tests {
    use super::*;
    use crate::{
        Underlying,
        instrument::{
            data_venue::DataVenue,
            kind::{InstrumentKind, cfd::CfdContract, perpetual::PerpetualContract},
            name::{InstrumentNameExchange, InstrumentNameInternal},
            quote::InstrumentQuoteAsset,
            spec::{
                InstrumentSpec, InstrumentSpecNotional, InstrumentSpecPrice, InstrumentSpecQuantity,
            },
        },
        test_utils::{exchange_asset, instrument},
    };
    use rust_decimal::Decimal;
    use rust_decimal_macros::dec;

    #[test]
    fn test_builder_basic_spot() {
        // Add single spot instrument
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(instrument(ExchangeId::BinanceSpot, "btc", "usdt"))
            .build();

        // Verify state
        assert_eq!(indexed.exchanges().len(), 1);
        assert_eq!(indexed.assets().len(), 2); // BTC and USDT
        assert_eq!(indexed.instruments().len(), 1);

        // Verify exchanges indexes
        assert_eq!(indexed.exchanges()[0].value, ExchangeId::BinanceSpot);

        // Verify asset indexes
        assert_eq!(
            indexed.assets()[0].value,
            exchange_asset(ExchangeId::BinanceSpot, "btc"),
        );
        assert_eq!(
            indexed.assets()[1].value,
            exchange_asset(ExchangeId::BinanceSpot, "usdt"),
        );

        // Very instrument indexes
        assert_eq!(
            indexed.instruments()[0].value,
            Instrument {
                exchange: Keyed::new(ExchangeIndex(0), ExchangeId::BinanceSpot),
                data_venue: None,
                name_exchange: InstrumentNameExchange::new("btc_usdt"),
                name_internal: InstrumentNameInternal::new("binance_spot-btc_usdt"),
                underlying: Underlying {
                    base: AssetIndex(0),
                    quote: AssetIndex(1),
                },
                quote: InstrumentQuoteAsset::UnderlyingQuote,
                kind: InstrumentKind::Spot,
                spec: None
            }
        );
    }

    #[test]
    fn add_asset_registers_an_asset_no_instrument_implies() {
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(instrument(ExchangeId::BinanceSpot, "btc", "usdt"))
            .add_asset(exchange_asset(ExchangeId::BinanceSpot, "bnb"))
            .build();

        assert_eq!(indexed.exchanges().len(), 1);
        let assets: Vec<_> = indexed.assets().iter().map(|a| &a.value).collect();
        assert_eq!(
            assets,
            [
                &exchange_asset(ExchangeId::BinanceSpot, "bnb"),
                &exchange_asset(ExchangeId::BinanceSpot, "btc"),
                &exchange_asset(ExchangeId::BinanceSpot, "usdt"),
            ]
        );

        // The instrument's assets still resolve by name after the fee asset sorts before them.
        let underlying = &indexed.instruments()[0].value.underlying;
        assert_eq!(
            indexed.assets()[underlying.base.index()]
                .value
                .asset
                .name_internal
                .as_ref(),
            "btc"
        );
        assert_eq!(
            indexed.assets()[underlying.quote.index()]
                .value
                .asset
                .name_internal
                .as_ref(),
            "usdt"
        );
    }

    #[test]
    fn add_asset_dedups_with_an_instrument_asset_and_registers_its_exchange() {
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(instrument(ExchangeId::BinanceSpot, "btc", "usdt"))
            .add_asset(exchange_asset(ExchangeId::BinanceSpot, "usdt"))
            .add_asset(exchange_asset(ExchangeId::Kraken, "bnb"))
            .build();

        assert_eq!(indexed.assets().len(), 3, "usdt once, plus Kraken's bnb");
        assert!(
            indexed
                .exchanges()
                .iter()
                .any(|exchange| exchange.value == ExchangeId::Kraken),
            "an asset's exchange is registered even with no instrument on it"
        );
    }

    #[test]
    fn add_asset_with_a_conflicting_name_fails_the_build() {
        let with = |asset: Asset| {
            IndexedInstrumentsBuilder::default()
                .add_instrument(instrument(ExchangeId::BinanceSpot, "btc", "usdt"))
                .add_asset(ExchangeAsset::new(ExchangeId::BinanceSpot, asset))
                .try_build()
        };

        assert!(matches!(
            with(Asset::new("usdt", "tether")),
            Err(IndexError::DuplicateAssetNameInternal(_))
        ));
        assert!(matches!(
            with(Asset::new("usdt_2", "USDT")),
            Err(IndexError::DuplicateAssetNameExchange(_))
        ));
    }

    #[test]
    fn test_builder_deduplication() {
        // Add same spot instrument twice
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(instrument(ExchangeId::BinanceSpot, "BTC", "USDT"))
            .add_instrument(instrument(ExchangeId::BinanceSpot, "BTC", "USDT"))
            .build();

        // Should deduplicate exchanges and assets, but not instruments
        assert_eq!(indexed.exchanges().len(), 1); // Exchange are de-duped
        assert_eq!(indexed.assets().len(), 2); // BTC and USDT and de-duped
        assert_eq!(indexed.instruments().len(), 1); // Instruments are de-duped
    }

    #[test]
    fn test_builder_rejects_duplicate_name_internal() {
        // Two genuinely DIFFERENT instruments that share a `name_internal`. The full-equality
        // `Instrument` dedup does not collapse these, so without the guard they would reach
        // `InstrumentStates` as one map entry, silently shifting every later `InstrumentIndex`
        // onto the wrong instrument.
        let shared_name = "binance_spot-btc_usdt";

        let build = |name_exchange| {
            Instrument::new(
                ExchangeId::BinanceSpot,
                shared_name,
                name_exchange,
                Underlying::new(
                    Asset::new_from_exchange("btc"),
                    Asset::new_from_exchange("usdt"),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                InstrumentKind::Spot,
                None,
            )
        };

        let error = IndexedInstrumentsBuilder::default()
            .add_instrument(build("BTCUSDT"))
            .add_instrument(build("BTC-USDT"))
            .try_build()
            .expect_err("duplicate name_internal must be rejected");

        let IndexError::DuplicateInstrumentNameInternal(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };

        // The message must name the duplicate and both instruments, or it cannot be acted on.
        assert!(message.contains(shared_name), "{message}");
        assert!(message.contains("BTCUSDT"), "{message}");
        assert!(message.contains("BTC-USDT"), "{message}");
        assert!(message.contains("binance_spot"), "{message}");
    }

    #[test]
    fn test_duplicate_name_internal_message_distinguishes_instruments_sharing_a_name_exchange() {
        // The collision this guard most plausibly catches: a spot and a CFD on one symbol, which is
        // the reason `Cfd` is a distinct kind at all. Both carry the same `name_exchange`, so a
        // message built from names alone reads "AAPL and AAPL on ibkr" -- asserting the two are
        // distinct while printing nothing that says how.
        let shared_name = "ibkr-aapl";

        let build = |kind| {
            Instrument::new(
                ExchangeId::Ibkr,
                shared_name,
                "AAPL",
                Underlying::new(
                    Asset::new_from_exchange("aapl"),
                    Asset::new_from_exchange("usd"),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                kind,
                None,
            )
        };

        let error = IndexedInstrumentsBuilder::default()
            .add_instrument(build(InstrumentKind::Spot))
            .add_instrument(build(InstrumentKind::Cfd(CfdContract {
                contract_size: Decimal::ONE,
                settlement_asset: Asset::new_from_exchange("usd"),
            })))
            .try_build()
            .expect_err("duplicate name_internal must be rejected");

        let IndexError::DuplicateInstrumentNameInternal(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };

        assert!(message.contains(shared_name), "{message}");
        // `kind` is the only field that differs, so it is the only thing that makes the message
        // actionable.
        assert!(message.contains("Spot"), "{message}");
        assert!(message.contains("Cfd"), "{message}");
    }

    #[test]
    fn test_duplicate_name_internal_message_distinguishes_instruments_sharing_everything_but_a_data_venue()
     {
        // The other axis a colliding pair can differ on while sharing `name_exchange` AND `kind`:
        // one symbol configured twice, priced on a different venue each time. `data_venue` is part
        // of `Instrument`s equality, so the dedup does not collapse these either -- and a message
        // built from `name_exchange` and `kind` alone would read "AAPL (Spot) and AAPL (Spot)".
        let shared_name = "ibkr-aapl";

        let build = |data_venue| {
            Instrument::new(
                ExchangeId::Ibkr,
                shared_name,
                "AAPL",
                Underlying::new(
                    Asset::new_from_exchange("aapl"),
                    Asset::new_from_exchange("usd"),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                InstrumentKind::Spot,
                None,
            )
            .with_data_venue(DataVenue::new_same_name(data_venue))
        };

        let error = IndexedInstrumentsBuilder::default()
            .add_instrument(build(ExchangeId::LseEquities))
            .add_instrument(build(ExchangeId::BinanceSpot))
            .try_build()
            .expect_err("duplicate name_internal must be rejected");

        let IndexError::DuplicateInstrumentNameInternal(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };

        assert!(message.contains(shared_name), "{message}");
        // The data venue is the only field that differs, so naming both is the only thing that
        // tells the operator which of the two configured entries to change.
        assert!(message.contains("lse_equities"), "{message}");
        assert!(message.contains("binance_spot"), "{message}");
    }

    #[test]
    fn test_duplicate_name_internal_message_distinguishes_instruments_differing_only_in_underlying()
    {
        // Neither `kind` nor `data_venue` differs here, so a message built from those alone would
        // read "BTCUSD (Spot) and BTCUSD (Spot)". The underlying is the field that tells them apart.
        let build = |quote| {
            Instrument::new(
                ExchangeId::BinanceSpot,
                "binance_spot-btc_usd",
                "BTCUSD",
                Underlying::new(
                    Asset::new_from_exchange("btc"),
                    Asset::new_from_exchange(quote),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                InstrumentKind::Spot,
                None,
            )
        };

        let error = IndexedInstrumentsBuilder::default()
            .add_instrument(build("usdt"))
            .add_instrument(build("usdc"))
            .try_build()
            .expect_err("duplicate name_internal must be rejected");

        let IndexError::DuplicateInstrumentNameInternal(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };

        assert!(message.contains("underlying btc/usdt"), "{message}");
        assert!(message.contains("underlying btc/usdc"), "{message}");
    }

    #[test]
    fn test_duplicate_name_internal_message_distinguishes_underlyings_differing_only_in_an_exchange_name()
     {
        // Both underlyings read `btc/usdt` by internal name, so only the assets' exchange-side
        // names tell them apart, and the message must reach for them.
        let build = |quote_name_exchange| {
            Instrument::new(
                ExchangeId::BinanceSpot,
                "binance_spot-btc_usdt",
                "BTCUSDT",
                Underlying::new(
                    Asset::new_from_exchange("btc"),
                    Asset::new("usdt", quote_name_exchange),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                InstrumentKind::Spot,
                None,
            )
        };

        let error = IndexedInstrumentsBuilder::default()
            .add_instrument(build("USDT"))
            .add_instrument(build("USDT-ERC20"))
            .try_build()
            .expect_err("duplicate name_internal must be rejected");

        let IndexError::DuplicateInstrumentNameInternal(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };

        assert!(message.contains("\"USDT\""), "{message}");
        assert!(message.contains("USDT-ERC20"), "{message}");
    }

    /// A spot and a CFD named `AAPL` on one venue, with distinct internal names: the
    /// `name_internal` check passes them, but every fill the venue reports for `AAPL` could resolve
    /// to either.
    fn aapl_on_ibkr(
        name_internal: &str,
        kind: InstrumentKind<Asset>,
    ) -> Instrument<ExchangeId, Asset> {
        Instrument::new(
            ExchangeId::Ibkr,
            name_internal,
            "AAPL",
            Underlying::new(
                Asset::new_from_exchange("aapl"),
                Asset::new_from_exchange("usd"),
            ),
            InstrumentQuoteAsset::UnderlyingQuote,
            kind,
            None,
        )
    }

    fn aapl_cfd() -> InstrumentKind<Asset> {
        InstrumentKind::Cfd(CfdContract {
            contract_size: Decimal::ONE,
            settlement_asset: Asset::new_from_exchange("usd"),
        })
    }

    #[test]
    fn two_instruments_sharing_a_name_exchange_on_one_exchange_are_rejected() {
        let error = IndexedInstrumentsBuilder::default()
            .add_instrument(aapl_on_ibkr("ibkr-aapl", InstrumentKind::Spot))
            .add_instrument(aapl_on_ibkr("ibkr-aapl-cfd", aapl_cfd()))
            .try_build()
            .expect_err("a duplicate (exchange, name_exchange) must be rejected");

        let IndexError::DuplicateInstrumentNameExchange(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };

        // The shared name, the exchange, and what tells the two entries apart.
        assert!(message.contains("AAPL on ibkr"), "{message}");
        assert!(message.contains("name_internal ibkr-aapl,"), "{message}");
        assert!(message.contains("ibkr-aapl-cfd"), "{message}");
        assert!(message.contains("Spot"), "{message}");
        assert!(message.contains("Cfd"), "{message}");
    }

    #[test]
    fn one_name_exchange_on_two_exchanges_is_not_a_collision() {
        let on_alpaca = Instrument::new(
            ExchangeId::AlpacaBroker,
            "alpaca-aapl",
            "AAPL",
            Underlying::new(
                Asset::new_from_exchange("aapl"),
                Asset::new_from_exchange("usd"),
            ),
            InstrumentQuoteAsset::UnderlyingQuote,
            InstrumentKind::Spot,
            None,
        );

        let instruments = IndexedInstrumentsBuilder::default()
            .add_instrument(aapl_on_ibkr("ibkr-aapl", InstrumentKind::Spot))
            .add_instrument(on_alpaca)
            .try_build()
            .expect("the same symbol on two exchanges must build");

        assert_eq!(instruments.instruments().len(), 2);
    }

    #[test]
    fn try_new_rejects_a_duplicate_name_exchange_too() {
        let result = IndexedInstruments::try_new([
            aapl_on_ibkr("ibkr-aapl", InstrumentKind::Spot),
            aapl_on_ibkr("ibkr-aapl-cfd", aapl_cfd()),
        ]);

        assert!(
            matches!(result, Err(IndexError::DuplicateInstrumentNameExchange(_))),
            "{result:?}"
        );
    }

    /// One exchange spelling a quote asset two ways, both normalising to `usdt`.
    fn spot_quoted_in(base: &str, quote_name_exchange: &str) -> Instrument<ExchangeId, Asset> {
        Instrument::spot(
            ExchangeId::BinanceSpot,
            format!("binance_spot-{base}_usdt"),
            format!("{}USDT", base.to_uppercase()),
            Underlying::new(
                Asset::new_from_exchange(base),
                Asset::new("usdt", quote_name_exchange),
            ),
            None,
        )
    }

    #[test]
    fn two_assets_sharing_a_name_internal_on_one_exchange_are_rejected() {
        let error = IndexedInstrumentsBuilder::default()
            .add_instrument(spot_quoted_in("btc", "USDT"))
            .add_instrument(spot_quoted_in("eth", "usdt.e"))
            .try_build()
            .expect_err("an (exchange, name_internal) asset collision must be rejected");

        let IndexError::DuplicateAssetNameInternal(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };
        assert!(message.contains("usdt on binance_spot"), "{message}");
        // Both spellings are named: they are the only thing telling the operator what collided.
        assert!(message.contains("USDT"), "{message}");
        assert!(message.contains("usdt.e"), "{message}");
    }

    #[test]
    fn two_instruments_whose_name_exchange_differs_only_in_case_are_rejected() {
        let mut lower = aapl_on_ibkr("ibkr-aapl-cfd", aapl_cfd());
        lower.name_exchange = InstrumentNameExchange::new("aapl");

        let error = IndexedInstrumentsBuilder::default()
            .add_instrument(aapl_on_ibkr("ibkr-aapl", InstrumentKind::Spot))
            .add_instrument(lower)
            .try_build()
            .expect_err("names that differ only in case are one name to the lookup");

        let IndexError::DuplicateInstrumentNameExchange(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };
        // Both spellings are named, and the message says why they collide.
        assert!(message.contains("AAPL"), "{message}");
        assert!(message.contains("aapl"), "{message}");
        assert!(message.contains("ignoring case"), "{message}");
    }

    #[test]
    fn two_assets_whose_name_exchange_differs_only_in_case_are_rejected() {
        let error = IndexedInstrumentsBuilder::default()
            .add_instrument(spot_quoted_in("btc", "USDT"))
            .add_instrument(Instrument::spot(
                ExchangeId::BinanceSpot,
                "binance_spot-eth_tether",
                "ETHTETHER",
                Underlying::new(
                    Asset::new_from_exchange("eth"),
                    Asset::new("tether", "usdt"),
                ),
                None,
            ))
            .try_build()
            .expect_err("an (exchange, name_exchange) asset collision must be rejected");

        let IndexError::DuplicateAssetNameExchange(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };
        assert!(message.contains("USDT"), "{message}");
        assert!(message.contains("usdt"), "{message}");
        assert!(message.contains("tether"), "{message}");
        assert!(message.contains("binance_spot"), "{message}");
    }

    #[test]
    fn two_assets_sharing_a_name_exchange_exactly_are_rejected() {
        // Before the name_exchange check, this pair built: two AssetIndex slots under one venue
        // name, of which the execution lookup could resolve only one.
        let result = IndexedInstruments::try_new([
            spot_quoted_in("btc", "USDT"),
            Instrument::spot(
                ExchangeId::BinanceSpot,
                "binance_spot-eth_tether",
                "ETHUSDT",
                Underlying::new(
                    Asset::new_from_exchange("eth"),
                    Asset::new("tether", "USDT"),
                ),
                None,
            ),
        ]);

        assert!(
            matches!(result, Err(IndexError::DuplicateAssetNameExchange(_))),
            "{result:?}"
        );
    }

    #[test]
    fn one_asset_name_internal_on_two_exchanges_is_not_a_collision() {
        let mut coinbase = spot_quoted_in("eth", "usdt.e");
        coinbase.exchange = ExchangeId::Coinbase;

        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(spot_quoted_in("btc", "USDT"))
            .add_instrument(coinbase)
            .try_build()
            .expect("an asset name is unique per exchange, not across exchanges");

        assert_eq!(indexed.assets().len(), 4);
    }

    /// Builds a one-instrument collection whose only variable is the CFD multiplier.
    fn cfd_with_contract_size(contract_size: Decimal) -> Result<IndexedInstruments, IndexError> {
        IndexedInstrumentsBuilder::default()
            .add_instrument(Instrument::new(
                ExchangeId::Ibkr,
                "ibkr-spx500_usd",
                "SPX500",
                Underlying::new(
                    Asset::new_from_exchange("spx500"),
                    Asset::new_from_exchange("usd"),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                InstrumentKind::Cfd(CfdContract {
                    contract_size,
                    settlement_asset: Asset::new_from_exchange("usd"),
                }),
                None,
            ))
            .try_build()
    }

    #[test]
    fn a_zero_contract_size_is_rejected_rather_than_silently_zeroing_notional_pnl_and_fees() {
        // Zero is the dangerous value precisely because nothing downstream fails on it: every
        // notional, fee and PnL becomes zero, so the run completes and reads as a strategy that
        // found no edge.
        let error = cfd_with_contract_size(Decimal::ZERO)
            .expect_err("a zero contract multiplier must be rejected");

        let IndexError::InvalidContractSize(message) = &error else {
            panic!("unexpected error variant: {error:?}")
        };

        // The message must identify which instrument carried it, or an operator with a hundred
        // configured instruments cannot act on it.
        assert!(message.contains("ibkr-spx500_usd"), "{message}");
        assert!(message.contains("ibkr"), "{message}");
    }

    #[test]
    fn a_negative_contract_size_is_rejected_rather_than_inverting_the_sign_of_pnl() {
        let error = cfd_with_contract_size(dec!(-25))
            .expect_err("a negative contract multiplier must be rejected");

        assert!(
            matches!(error, IndexError::InvalidContractSize(_)),
            "unexpected error variant: {error:?}"
        );
    }

    #[test]
    fn a_positive_contract_size_builds() {
        // The control: the guard must reject only the degenerate values. €25-per-point is an
        // ordinary index CFD multiplier, not an edge case.
        let indexed = cfd_with_contract_size(dec!(25)).expect("a positive multiplier is valid");

        assert_eq!(indexed.instruments().len(), 1);
        assert_eq!(
            indexed.instruments()[0].value.kind.contract_size(),
            dec!(25)
        );
    }

    #[test]
    fn the_contract_size_guard_covers_every_kind_that_carries_one() {
        // The check reads `InstrumentKind::contract_size`, so it is uniform by construction -- but
        // that is the property worth pinning, since a future kind gaining a multiplier inherits
        // the guard for free only as long as it reports through that accessor.
        let usd = || Asset::new_from_exchange("usd");

        let kinds = [
            InstrumentKind::Perpetual(PerpetualContract {
                contract_size: Decimal::ZERO,
                settlement_asset: usd(),
            }),
            InstrumentKind::Cfd(CfdContract {
                contract_size: Decimal::ZERO,
                settlement_asset: usd(),
            }),
        ];

        for kind in kinds {
            let error = IndexedInstrumentsBuilder::default()
                .add_instrument(Instrument::new(
                    ExchangeId::Ibkr,
                    "ibkr-aapl",
                    "AAPL",
                    Underlying::new(Asset::new_from_exchange("aapl"), usd()),
                    InstrumentQuoteAsset::UnderlyingQuote,
                    kind.clone(),
                    None,
                ))
                .try_build()
                .expect_err("a zero contract multiplier must be rejected on every kind");

            assert!(
                matches!(error, IndexError::InvalidContractSize(_)),
                "{kind:?} was not guarded: {error:?}"
            );
        }

        // `Spot` reports a hard `Decimal::ONE` and therefore cannot trip the guard -- pinned so a
        // future change to that accessor cannot make every spot collection unbuildable.
        assert!(
            IndexedInstrumentsBuilder::default()
                .add_instrument(instrument(ExchangeId::BinanceSpot, "btc", "usdt"))
                .try_build()
                .is_ok()
        );
    }

    #[test]
    fn try_new_applies_the_same_collection_invariants_as_the_builder() {
        // `IndexedInstruments::try_new` is the entry point config-derived collections actually
        // take, and it folds into the builder -- but nothing pinned that, so a future
        // reimplementation could bypass `try_build` and lose both guards silently.
        let duplicate = |name_exchange| {
            Instrument::new(
                ExchangeId::BinanceSpot,
                "binance_spot-btc_usdt",
                name_exchange,
                Underlying::new(
                    Asset::new_from_exchange("btc"),
                    Asset::new_from_exchange("usdt"),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                InstrumentKind::Spot,
                None,
            )
        };

        assert!(matches!(
            IndexedInstruments::try_new([duplicate("BTCUSDT"), duplicate("BTC-USDT")]),
            Err(IndexError::DuplicateInstrumentNameInternal(_))
        ));

        assert!(matches!(
            IndexedInstruments::try_new([Instrument::new(
                ExchangeId::Ibkr,
                "ibkr-spx500_usd",
                "SPX500",
                Underlying::new(
                    Asset::new_from_exchange("spx500"),
                    Asset::new_from_exchange("usd"),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                InstrumentKind::Cfd(CfdContract {
                    contract_size: Decimal::ZERO,
                    settlement_asset: Asset::new_from_exchange("usd"),
                }),
                None,
            )]),
            Err(IndexError::InvalidContractSize(_))
        ));

        // And the valid case still builds, so the assertions above are not passing on a
        // constructor that rejects everything.
        let indexed = IndexedInstruments::try_new([
            instrument(ExchangeId::BinanceSpot, "btc", "usdt"),
            instrument(ExchangeId::BinanceSpot, "eth", "usdt"),
        ])
        .expect("two distinct spot instruments are a valid collection");

        assert_eq!(indexed.instruments().len(), 2);
        assert_eq!(indexed.exchanges().len(), 1);
        // BTC, ETH, USDT -- the shared quote is indexed once.
        assert_eq!(indexed.assets().len(), 3);
    }

    #[test]
    #[should_panic(expected = "invalid contract_size")]
    fn new_panics_on_an_invalid_collection_rather_than_indexing_it() {
        // The infallible convenience must not be a way around the guard.
        let _ = IndexedInstruments::new([Instrument::new(
            ExchangeId::Ibkr,
            "ibkr-spx500_usd",
            "SPX500",
            Underlying::new(
                Asset::new_from_exchange("spx500"),
                Asset::new_from_exchange("usd"),
            ),
            InstrumentQuoteAsset::UnderlyingQuote,
            InstrumentKind::Cfd(CfdContract {
                contract_size: Decimal::ZERO,
                settlement_asset: Asset::new_from_exchange("usd"),
            }),
            None,
        )]);
    }

    #[test]
    #[should_panic(expected = "duplicate InstrumentNameInternal")]
    fn test_builder_build_panics_on_duplicate_name_internal() {
        let build = |name_exchange| {
            Instrument::new(
                ExchangeId::BinanceSpot,
                "binance_spot-btc_usdt",
                name_exchange,
                Underlying::new(
                    Asset::new_from_exchange("btc"),
                    Asset::new_from_exchange("usdt"),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                InstrumentKind::Spot,
                None,
            )
        };

        let _ = IndexedInstrumentsBuilder::default()
            .add_instrument(build("BTCUSDT"))
            .add_instrument(build("BTC-USDT"))
            .build();
    }

    #[test]
    fn test_builder_exact_duplicate_instruments_are_not_a_name_collision() {
        // The same instrument added twice is legitimate input -- the pre-existing dedup collapses
        // it to one -- so the uniqueness guard must not fire. Pins the guard's position after the
        // dedup rather than before it.
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(instrument(ExchangeId::BinanceSpot, "btc", "usdt"))
            .add_instrument(instrument(ExchangeId::BinanceSpot, "btc", "usdt"))
            .try_build()
            .expect("exact duplicates are deduped, not a name collision");

        assert_eq!(indexed.instruments().len(), 1);
    }

    /// An `AAPL` executed on Alpaca but priced by LSE — the same-kind data-venue substitution the
    /// field exists for.
    fn dual_venue_instrument() -> Instrument<ExchangeId, Asset> {
        Instrument::spot(
            ExchangeId::AlpacaBroker,
            "alpaca_broker-aapl",
            "AAPL",
            Underlying::new(
                Asset::new_from_exchange("aapl"),
                Asset::new_from_exchange("usd"),
            ),
            None,
        )
        .with_data_venue(DataVenue::new_same_name(ExchangeId::LseEquities))
    }

    #[test]
    fn a_data_only_venue_is_indexed_so_it_can_carry_connectivity_state() {
        // The registration that makes a data-only venue expressible at all: it appears on no
        // instrument's `exchange`, so without this it would have no `ExchangeIndex` and no
        // `ConnectivityState`, and its first market event would hit a missing-exchange lookup.
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(dual_venue_instrument())
            .try_build()
            .expect("a dual-venue instrument is a valid collection");

        let exchanges = indexed
            .exchanges()
            .iter()
            .map(|keyed| keyed.value)
            .collect::<Vec<_>>();

        assert!(
            exchanges.contains(&ExchangeId::AlpacaBroker),
            "{exchanges:?}"
        );
        assert!(
            exchanges.contains(&ExchangeId::LseEquities),
            "{exchanges:?}"
        );
    }

    #[test]
    fn a_data_only_venue_contributes_no_assets() {
        // A data-only venue holds no balances, and `ExchangeAsset` keys balance state. Registering
        // its assets would seed balances for an account that does not exist, and double the asset
        // index space for every dual-venue instrument.
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(dual_venue_instrument())
            .try_build()
            .expect("a dual-venue instrument is a valid collection");

        // AAPL and USD, on the execution venue only.
        assert_eq!(indexed.assets().len(), 2);
        assert!(
            indexed
                .assets()
                .iter()
                .all(|keyed| keyed.value.exchange == ExchangeId::AlpacaBroker),
            "{:?}",
            indexed.assets()
        );
    }

    #[test]
    fn a_dual_venue_instrument_carries_the_data_venues_own_exchange_index() {
        // The indexing must resolve the data venue against the data venue -- stamping the
        // execution venue's key onto it would point market-data state at the wrong exchange, with
        // nothing at runtime to signal it.
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(dual_venue_instrument())
            .try_build()
            .expect("a dual-venue instrument is a valid collection");

        let instrument = &indexed.instruments()[0].value;

        let data_venue = instrument
            .data_venue
            .as_ref()
            .expect("the data venue survives indexing");

        assert_eq!(data_venue.exchange.value, ExchangeId::LseEquities);
        assert_ne!(data_venue.exchange.key, instrument.exchange.key);

        // And the key is the one the exchange index actually assigned to LSE.
        let expected = indexed
            .exchanges()
            .iter()
            .find(|keyed| keyed.value == ExchangeId::LseEquities)
            .expect("LSE is indexed")
            .key;
        assert_eq!(data_venue.exchange.key, expected);
    }

    #[test]
    fn a_data_venue_pointing_at_the_execution_venue_does_not_duplicate_the_exchange() {
        // Degenerate but legal: stating the data venue explicitly when it is the same venue. The
        // exchange dedup must absorb it, or the venue would be indexed twice and every later
        // ExchangeIndex would shift.
        let builder = IndexedInstrumentsBuilder::default().add_instrument(
            instrument(ExchangeId::BinanceSpot, "btc", "usdt")
                .with_data_venue(DataVenue::new_same_name(ExchangeId::BinanceSpot)),
        );

        // Asserted before the build, because the post-build count alone would also hold if
        // `add_instrument` never registered the data venue at all -- which is the bug this test
        // must not pass through. The registration is unconditional; the dedup is what makes the
        // degenerate case harmless.
        assert_eq!(
            builder.exchanges,
            vec![ExchangeId::BinanceSpot; 2],
            "the data venue is registered unconditionally, whatever venue it names",
        );

        let indexed = builder
            .try_build()
            .expect("a self-referential data venue is valid, if redundant");

        assert_eq!(indexed.exchanges().len(), 1);
    }

    #[test]
    fn test_builder_multiple_exchanges() {
        // Add instruments from different exchanges
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(instrument(ExchangeId::BinanceSpot, "BTC", "USDT"))
            .add_instrument(instrument(ExchangeId::Coinbase, "BTC", "USD"))
            .build();

        // Should maintain separate indices for same asset on different exchanges
        assert_eq!(indexed.exchanges().len(), 2);
        assert_eq!(indexed.assets().len(), 4); // BTC on both exchanges, USDT and USD
        assert_eq!(indexed.instruments().len(), 2);
    }

    #[test]
    fn test_builder_asset_unit_handling() {
        // Create instrument with asset-based order quantity
        let base_asset = Asset::new_from_exchange("BTC");
        let quote_asset = Asset::new_from_exchange("USDT");

        let instrument = Instrument::new(
            ExchangeId::BinanceSpot,
            "binance_spot_btc_usdt",
            "BTC-USDT",
            Underlying::new(base_asset.clone(), quote_asset.clone()),
            InstrumentQuoteAsset::UnderlyingQuote,
            InstrumentKind::Spot,
            Some(InstrumentSpec {
                price: InstrumentSpecPrice {
                    min: dec!(0.1),
                    tick_size: dec!(0.1),
                },
                quantity: InstrumentSpecQuantity {
                    unit: OrderQuantityUnits::Asset(base_asset.clone()),
                    min: dec!(0.001),
                    increment: dec!(0.001),
                },
                notional: InstrumentSpecNotional { min: dec!(10) },
            }),
        );

        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(instrument)
            .build();

        // Should index the asset used in OrderQuantityUnits
        assert_eq!(indexed.assets().len(), 2);
        assert_eq!(
            indexed.assets()[0].value,
            exchange_asset(ExchangeId::BinanceSpot, "BTC")
        );
    }

    #[test]
    fn test_builder_ordering() {
        // Add instruments in any order
        let indexed = IndexedInstrumentsBuilder::default()
            .add_instrument(instrument(ExchangeId::BinanceSpot, "BTC", "USDT"))
            .add_instrument(instrument(ExchangeId::Coinbase, "ETH", "USD"))
            .build();

        // Verify exchanges are ordered by input sequence
        assert_eq!(indexed.exchanges()[0].value, ExchangeId::BinanceSpot);
        assert_eq!(indexed.exchanges()[1].value, ExchangeId::Coinbase);

        // Verify exchanges are ordered by input sequence
        assert_eq!(
            indexed.assets()[0].value,
            exchange_asset(ExchangeId::BinanceSpot, "BTC")
        );
        assert_eq!(
            indexed.assets()[1].value,
            exchange_asset(ExchangeId::BinanceSpot, "USDT")
        );
        assert_eq!(
            indexed.assets()[2].value,
            exchange_asset(ExchangeId::Coinbase, "ETH")
        );
        assert_eq!(
            indexed.assets()[3].value,
            exchange_asset(ExchangeId::Coinbase, "USD")
        );

        // Verify instruments are ordered by input sequence
        assert_eq!(
            indexed.instruments()[0].value,
            Instrument {
                exchange: Keyed::new(ExchangeIndex(0), ExchangeId::BinanceSpot),
                data_venue: None,
                name_exchange: InstrumentNameExchange::new("BTC_USDT"),
                name_internal: InstrumentNameInternal::new("binance_spot-btc_usdt"),
                underlying: Underlying {
                    base: AssetIndex(0),
                    quote: AssetIndex(1),
                },
                quote: InstrumentQuoteAsset::UnderlyingQuote,
                kind: InstrumentKind::Spot,
                spec: None
            }
        );

        assert_eq!(
            indexed.instruments()[1].value,
            Instrument {
                exchange: Keyed::new(ExchangeIndex(1), ExchangeId::Coinbase),
                data_venue: None,
                name_exchange: InstrumentNameExchange::new("ETH_USD"),
                name_internal: InstrumentNameInternal::new("coinbase-eth_usd"),
                underlying: Underlying {
                    base: AssetIndex(2),
                    quote: AssetIndex(3),
                },
                quote: InstrumentQuoteAsset::UnderlyingQuote,
                kind: InstrumentKind::Spot,
                spec: None
            }
        );
    }
}