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
use crate::{
    Keyed,
    asset::{Asset, AssetIndex, ExchangeAsset, name::AssetNameInternal},
    exchange::{ExchangeId, ExchangeIndex},
    index::{builder::IndexedInstrumentsBuilder, error::IndexError},
    instrument::{Instrument, InstrumentIndex, name::InstrumentNameInternal},
};
use serde::{Deserialize, Serialize, Serializer, ser::SerializeSeq};

pub mod builder;

/// Contains error variants that can occur when working with an [`IndexedInstruments`] collection.
pub mod error;

/// Indexed collection of exchanges, assets, and instruments.
///
/// Initialise incrementally via the [`IndexedInstrumentsBuilder`], or all at once via the
/// constructor.
///
/// The indexed collection is useful for creating efficient O(1) constant lookup state management
/// systems where the state is keyed on an instrument, asset, or exchange.
///
/// For example uses cases, see the central `rustrade` crate `EngineState` design.
///
/// # Index Relationships
/// - `ExchangeIndex`: Unique index for each [`ExchangeId`] added during initialisation.
/// - `InstrumentIndex`: Unique identifier for each [`Instrument`] added during initialisation.
/// - `AssetIndex`: Unique identifier for each [`ExchangeAsset`] added during initialisation.
///
/// # Serialisation
/// Serialises as the plain list of unindexed `Instrument<ExchangeId, Asset>`s it indexes, and
/// deserialises from that list through [`Self::try_new`]. No index is ever read from a payload,
/// so a deserialised collection upholds every invariant a built one does, and a payload that
/// breaks one fails with the same [`IndexError`] `try_new` returns. Building sorts and
/// de-duplicates, and every asset is derived from the instruments and unique by exchange and
/// [`AssetNameInternal`], so a round trip reproduces the same indices.
#[derive(Debug, Clone, PartialEq, PartialOrd, Deserialize)]
#[serde(try_from = "Vec<Instrument<ExchangeId, Asset>>")]
pub struct IndexedInstruments {
    exchanges: Vec<Keyed<ExchangeIndex, ExchangeId>>,
    assets: Vec<Keyed<AssetIndex, ExchangeAsset<Asset>>>,
    instruments:
        Vec<Keyed<InstrumentIndex, Instrument<Keyed<ExchangeIndex, ExchangeId>, AssetIndex>>>,
}

impl IndexedInstruments {
    /// Initialises a new `IndexedInstruments` from an iterator of [`Instrument`]s.
    ///
    /// This method indexes all unique exchanges, assets, and instruments, creating efficient
    /// lookup tables for each entity type.
    ///
    /// Note that once an `IndexedInstruments` has been constructed, it cannot be mutated (this
    /// could invalidate existing index lookup tables).
    ///
    /// For incremental initialisation, see the [`IndexedInstrumentsBuilder`].
    ///
    /// # Panics
    /// Panics if the provided `Instrument`s are not a valid collection — see [`Self::try_new`],
    /// which returns that as an [`IndexError`] instead.
    pub fn new<Iter, I>(instruments: Iter) -> Self
    where
        Iter: IntoIterator<Item = I>,
        I: Into<Instrument<ExchangeId, Asset>>,
    {
        // Deliberate panic: `new` is the infallible convenience over `try_new`, and mirrors
        // `IndexedInstrumentsBuilder::build`. `FromIterator` cannot return a `Result`, so an
        // infallible constructor has to exist regardless.
        #[allow(clippy::panic)] // Documented in this method's `# Panics` section.
        Self::try_new(instruments)
            .unwrap_or_else(|error| panic!("failed to build IndexedInstruments: {error}"))
    }

    /// Initialises a new `IndexedInstruments` from an iterator of [`Instrument`]s, returning an
    /// [`IndexError`] if they are not a valid collection.
    ///
    /// # Errors
    /// Returns [`IndexError::DuplicateInstrumentNameInternal`] if two `Instrument`s share an
    /// [`InstrumentNameInternal`], [`IndexError::DuplicateInstrumentNameExchange`] if two on one
    /// exchange share an [`InstrumentNameExchange`](crate::instrument::name::InstrumentNameExchange),
    /// [`IndexError::DuplicateAssetNameInternal`] if two distinct assets on one exchange share an
    /// [`AssetNameInternal`], or [`IndexError::InvalidContractSize`] if an `Instrument` carries a
    /// non-positive `contract_size` — see [`IndexedInstrumentsBuilder::try_build`] for why each
    /// invariant exists.
    pub fn try_new<Iter, I>(instruments: Iter) -> Result<Self, IndexError>
    where
        Iter: IntoIterator<Item = I>,
        I: Into<Instrument<ExchangeId, Asset>>,
    {
        instruments
            .into_iter()
            .fold(Self::builder(), |builder, instrument| {
                builder.add_instrument(instrument.into())
            })
            .try_build()
    }

    /// Returns a new [`IndexedInstrumentsBuilder`] useful for incremental initialisation of
    /// `IndexedInstruments`.
    pub fn builder() -> IndexedInstrumentsBuilder {
        IndexedInstrumentsBuilder::default()
    }

    /// Returns a reference to the [`ExchangeIndex`] <--> [`ExchangeId`] associations.
    pub fn exchanges(&self) -> &[Keyed<ExchangeIndex, ExchangeId>] {
        &self.exchanges
    }

    /// Returns a reference to the [`AssetIndex`] <--> [`ExchangeAsset`] associations.
    pub fn assets(&self) -> &[Keyed<AssetIndex, ExchangeAsset<Asset>>] {
        &self.assets
    }

    /// Returns a reference to the [`InstrumentIndex`] <--> [`Instrument`] associations.
    pub fn instruments(
        &self,
    ) -> &[Keyed<InstrumentIndex, Instrument<Keyed<ExchangeIndex, ExchangeId>, AssetIndex>>] {
        &self.instruments
    }

    /// Finds the [`ExchangeIndex`] associated with the provided [`ExchangeId`].
    ///
    /// # Arguments
    /// * `exchange` - The exchange ID to look up
    ///
    /// # Returns
    /// * `Ok(ExchangeIndex)` - exchange found.
    /// * `Err(IndexError)` - exchange not found.
    pub fn find_exchange_index(&self, exchange: ExchangeId) -> Result<ExchangeIndex, IndexError> {
        find_exchange_by_exchange_id(&self.exchanges, &exchange)
    }

    pub fn find_exchange(&self, index: ExchangeIndex) -> Result<ExchangeId, IndexError> {
        self.exchanges
            .iter()
            .find(|keyed| keyed.key == index)
            .map(|keyed| keyed.value)
            .ok_or(IndexError::ExchangeIndex(format!(
                "ExchangeIndex: {index} is not present in indexed instrument exchanges"
            )))
    }

    /// Finds the [`AssetIndex`] associated with the provided `ExchangeId` and `AssetNameInterval`.
    ///
    /// # Arguments
    /// * `exchange` - The `ExchangeId` associated with the asset.
    /// * `name` - The `AssetNameInternal` associated with the asset (eg/ "btc", "usdt", etc).
    ///
    /// # Returns
    /// * `Ok(AssetIndex)` - exchange asset found.
    /// * `Err(IndexError)` - exchange asset not found.
    pub fn find_asset_index(
        &self,
        exchange: ExchangeId,
        name: &AssetNameInternal,
    ) -> Result<AssetIndex, IndexError> {
        find_asset_by_exchange_and_name_internal(&self.assets, exchange, name)
    }

    pub fn find_asset(&self, index: AssetIndex) -> Result<&ExchangeAsset<Asset>, IndexError> {
        self.assets
            .iter()
            .find(|keyed| keyed.key == index)
            .map(|keyed| &keyed.value)
            .ok_or(IndexError::AssetIndex(format!(
                "AssetIndex: {index} is not present in indexed instrument assets"
            )))
    }

    /// Finds the [`InstrumentIndex`] associated with the provided `ExchangeId` and
    /// `InstrumentNameInternal`.
    ///
    /// # Arguments
    /// * `exchange` - The `ExchangeId` associated with the instrument.
    /// * `name` - The `InstrumentNameInternal` associated with the instrument (eg/ binance_spot_btc_usdt).
    ///
    /// # Returns
    /// * `Ok(InstrumentIndex)` - instrument found.
    /// * `Err(IndexError::InstrumentIndex)` - instrument not found.
    pub fn find_instrument_index(
        &self,
        exchange: ExchangeId,
        name: &InstrumentNameInternal,
    ) -> Result<InstrumentIndex, IndexError> {
        self.instruments
            .iter()
            .find_map(|indexed| {
                (indexed.value.exchange.value == exchange && indexed.value.name_internal == *name)
                    .then_some(indexed.key)
            })
            .ok_or_else(|| {
                IndexError::InstrumentIndex(format!(
                    "Instrument: ({exchange}, {name}) is not present in indexed instruments: {:?}",
                    self.instruments
                        .iter()
                        .map(|keyed| format!(
                            "({}, {})",
                            keyed.value.exchange.value, keyed.value.name_internal
                        ))
                        .collect::<Vec<_>>()
                ))
            })
    }

    pub fn find_instrument(
        &self,
        index: InstrumentIndex,
    ) -> Result<&Instrument<Keyed<ExchangeIndex, ExchangeId>, AssetIndex>, IndexError> {
        self.instruments
            .iter()
            .find(|keyed| keyed.key == index)
            .map(|keyed| &keyed.value)
            .ok_or(IndexError::InstrumentIndex(format!(
                "InstrumentIndex: {index} is not present in indexed instrument instruments"
            )))
    }
}

impl IndexedInstruments {
    /// The unindexed form of an indexed `instrument`, with each [`AssetIndex`] resolved
    /// positionally against `self.assets`.
    fn unindexed_instrument(
        &self,
        instrument: &Instrument<Keyed<ExchangeIndex, ExchangeId>, AssetIndex>,
    ) -> Result<Instrument<ExchangeId, Asset>, IndexError> {
        instrument
            .clone()
            .map_exchange_key(|exchange| exchange.value)
            .map_asset_key_with_lookup(|index| {
                self.assets
                    .get(index.index())
                    .filter(|keyed| keyed.key == *index)
                    .map(|keyed| keyed.value.asset.clone())
                    .ok_or_else(|| {
                        IndexError::AssetIndex(format!(
                            "AssetIndex: {index} of instrument {} is not present in indexed \
                             instrument assets",
                            instrument.name_internal
                        ))
                    })
            })
    }
}

impl Serialize for IndexedInstruments {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.instruments.len()))?;
        for keyed in &self.instruments {
            let instrument = self
                .unindexed_instrument(&keyed.value)
                .map_err(serde::ser::Error::custom)?;
            seq.serialize_element(&instrument)?;
        }
        seq.end()
    }
}

impl TryFrom<Vec<Instrument<ExchangeId, Asset>>> for IndexedInstruments {
    type Error = IndexError;

    /// Builds the collection through [`IndexedInstruments::try_new`].
    fn try_from(instruments: Vec<Instrument<ExchangeId, Asset>>) -> Result<Self, Self::Error> {
        Self::try_new(instruments)
    }
}

impl<I> FromIterator<I> for IndexedInstruments
where
    I: Into<Instrument<ExchangeId, Asset>>,
{
    fn from_iter<Iter>(iter: Iter) -> Self
    where
        Iter: IntoIterator<Item = I>,
    {
        Self::new(iter)
    }
}

fn find_exchange_by_exchange_id(
    haystack: &[Keyed<ExchangeIndex, ExchangeId>],
    needle: &ExchangeId,
) -> Result<ExchangeIndex, IndexError> {
    haystack
        .iter()
        .find_map(|indexed| (indexed.value == *needle).then_some(indexed.key))
        .ok_or(IndexError::ExchangeIndex(format!(
            "Exchange: {needle} is not present in indexed instrument exchanges: {haystack:?}"
        )))
}

fn find_asset_by_exchange_and_name_internal(
    haystack: &[Keyed<AssetIndex, ExchangeAsset<Asset>>],
    needle_exchange: ExchangeId,
    needle_name: &AssetNameInternal,
) -> Result<AssetIndex, IndexError> {
    haystack
        .iter()
        .find_map(|indexed| {
            (indexed.value.exchange == needle_exchange
                && indexed.value.asset.name_internal == *needle_name)
                .then_some(indexed.key)
        })
        .ok_or(IndexError::AssetIndex(format!(
            "Asset: ({needle_exchange}, {needle_name}) is not present in indexed instrument assets: {haystack:?}"
        )))
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
mod tests {
    use super::*;

    use crate::{
        Underlying,
        asset::Asset,
        exchange::ExchangeId,
        instrument::{
            kind::InstrumentKind, name::InstrumentNameExchange, quote::InstrumentQuoteAsset,
        },
        test_utils::{exchange_asset, instrument},
    };
    use rust_decimal::Decimal;

    #[test]
    fn test_indexed_instruments_new() {
        // Test creating empty IndexedInstruments
        let empty = IndexedInstruments::new(std::iter::empty::<Instrument<ExchangeId, Asset>>());
        assert!(empty.exchanges().is_empty());
        assert!(empty.assets().is_empty());
        assert!(empty.instruments().is_empty());

        // Test creating with single instrument
        let instrument = instrument(ExchangeId::BinanceSpot, "btc", "usdt");
        let actual = IndexedInstruments::new(std::iter::once(instrument));

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

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

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

        // Very instrument indexes
        assert_eq!(
            actual.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 test_indexed_instruments_multiple() {
        let instruments = vec![
            instrument(ExchangeId::BinanceSpot, "BTC", "USDT"),
            instrument(ExchangeId::BinanceSpot, "ETH", "USDT"),
            instrument(ExchangeId::Coinbase, "BTC", "USD"),
        ];

        let indexed = IndexedInstruments::new(instruments);

        // Should have 2 exchanges, 4 assets (BTC, ETH, USDT, USD), and 3 instruments
        assert_eq!(indexed.exchanges().len(), 2);
        assert_eq!(indexed.assets().len(), 5);
        assert_eq!(indexed.instruments().len(), 3);

        // Verify exchanges
        let exchanges: Vec<_> = indexed.exchanges().iter().map(|e| e.value).collect();
        assert!(exchanges.contains(&ExchangeId::BinanceSpot));
        assert!(exchanges.contains(&ExchangeId::Coinbase));
    }

    #[test]
    fn test_find_exchange_index() {
        let instruments = vec![
            instrument(ExchangeId::BinanceSpot, "BTC", "USDT"),
            instrument(ExchangeId::Coinbase, "ETH", "USD"),
        ];
        let indexed = IndexedInstruments::new(instruments);

        // Test finding existing exchanges
        assert!(indexed.find_exchange_index(ExchangeId::BinanceSpot).is_ok());
        assert!(indexed.find_exchange_index(ExchangeId::Coinbase).is_ok());

        // Test finding non-existent exchange
        let err = indexed.find_exchange_index(ExchangeId::Kraken).unwrap_err();
        assert!(matches!(err, IndexError::ExchangeIndex(_)));
    }

    #[test]
    fn test_find_asset_index() {
        let instruments = vec![
            instrument(ExchangeId::BinanceSpot, "BTC", "USDT"),
            instrument(ExchangeId::Coinbase, "ETH", "USD"),
        ];
        let indexed = IndexedInstruments::new(instruments);

        // Test finding existing assets
        assert!(
            indexed
                .find_asset_index(ExchangeId::BinanceSpot, &AssetNameInternal::from("btc"))
                .is_ok()
        );
        assert!(
            indexed
                .find_asset_index(ExchangeId::BinanceSpot, &AssetNameInternal::from("usdt"))
                .is_ok()
        );
        assert!(
            indexed
                .find_asset_index(ExchangeId::Coinbase, &AssetNameInternal::from("eth"))
                .is_ok()
        );

        // Test finding asset with wrong exchange
        let err = indexed
            .find_asset_index(ExchangeId::Kraken, &AssetNameInternal::from("btc"))
            .unwrap_err();
        assert!(matches!(err, IndexError::AssetIndex(_)));

        // Test finding non-existent asset
        let err = indexed
            .find_asset_index(
                ExchangeId::BinanceSpot,
                &AssetNameInternal::from("nonexistent"),
            )
            .unwrap_err();
        assert!(matches!(err, IndexError::AssetIndex(_)));
    }

    #[test]
    fn test_find_instrument_index() {
        let instruments = vec![
            instrument(ExchangeId::BinanceSpot, "btc", "usdt"),
            instrument(ExchangeId::Coinbase, "eth", "usd"),
        ];

        let indexed = IndexedInstruments::new(instruments);
        let btc_usdt = InstrumentNameInternal::from("binance_spot-btc_usdt");

        // Test finding existing instruments
        assert!(
            indexed
                .find_instrument_index(ExchangeId::BinanceSpot, &btc_usdt)
                .is_ok()
        );

        // Test finding instrument with wrong exchange
        let err = indexed
            .find_instrument_index(ExchangeId::Kraken, &btc_usdt)
            .unwrap_err();
        assert!(matches!(err, IndexError::InstrumentIndex(_)));

        // Test finding non-existent instrument: the error names the instrument sought and lists
        // the instruments searched, not the assets
        let nonexistent = InstrumentNameInternal::from("nonexistent");
        let err = indexed
            .find_instrument_index(ExchangeId::BinanceSpot, &nonexistent)
            .unwrap_err();
        let IndexError::InstrumentIndex(message) = err else {
            panic!("expected IndexError::InstrumentIndex, got {err:?}");
        };
        assert!(message.contains("(binance_spot, nonexistent)"), "{message}");
        assert!(message.contains("binance_spot-btc_usdt"), "{message}");
        assert!(!message.contains("ExchangeAsset"), "{message}");
    }

    #[test]
    fn test_private_find_exchange_by_exchange_id() {
        let exchanges = vec![
            Keyed {
                key: ExchangeIndex(0),
                value: ExchangeId::BinanceSpot,
            },
            Keyed {
                key: ExchangeIndex(1),
                value: ExchangeId::Coinbase,
            },
        ];

        // Test finding existing exchange
        let result = find_exchange_by_exchange_id(&exchanges, &ExchangeId::BinanceSpot);
        assert_eq!(result.unwrap(), ExchangeIndex(0));

        // Test finding non-existent exchange
        let err = find_exchange_by_exchange_id(&exchanges, &ExchangeId::Kraken).unwrap_err();
        assert!(matches!(err, IndexError::ExchangeIndex(_)));
    }

    #[test]
    fn test_private_find_asset_by_exchange_and_name_internal() {
        let assets = vec![
            Keyed {
                key: AssetIndex(0),
                value: ExchangeAsset {
                    exchange: ExchangeId::BinanceSpot,
                    asset: Asset::new_from_exchange("BTC"),
                },
            },
            Keyed {
                key: AssetIndex(1),
                value: ExchangeAsset {
                    exchange: ExchangeId::BinanceSpot,
                    asset: Asset::new_from_exchange("USDT"),
                },
            },
        ];

        // Test finding existing asset
        let result = find_asset_by_exchange_and_name_internal(
            &assets,
            ExchangeId::BinanceSpot,
            &AssetNameInternal::from("btc"),
        );
        assert_eq!(result.unwrap(), AssetIndex(0));

        // Test finding asset with wrong exchange
        let err = find_asset_by_exchange_and_name_internal(
            &assets,
            ExchangeId::Kraken,
            &AssetNameInternal::from("btc"),
        )
        .unwrap_err();
        assert!(matches!(err, IndexError::AssetIndex(_)));

        // Test finding non-existent asset
        let err = find_asset_by_exchange_and_name_internal(
            &assets,
            ExchangeId::BinanceSpot,
            &AssetNameInternal::from("nonexistent"),
        )
        .unwrap_err();
        assert!(matches!(err, IndexError::AssetIndex(_)));
    }

    #[test]
    fn test_duplicates_are_filtered_correctly() {
        // Test with duplicate instruments
        let instruments = vec![
            instrument(ExchangeId::BinanceSpot, "btc", "usdt"),
            instrument(ExchangeId::BinanceSpot, "btc", "usdt"),
        ];
        let indexed = IndexedInstruments::new(instruments);

        // Should deduplicate exchanges and assets
        assert_eq!(indexed.exchanges().len(), 1);
        assert_eq!(indexed.assets().len(), 2);
        assert_eq!(indexed.instruments().len(), 1); // Instruments aren't deduplicated

        // Test with same asset on different exchanges
        let instruments = vec![
            instrument(ExchangeId::BinanceSpot, "btc", "usdt"),
            instrument(ExchangeId::Coinbase, "btc", "usdt"),
        ];
        let indexed = IndexedInstruments::new(instruments);

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

    /// A multi-exchange set exercising every key `map_exchange_key` and
    /// `map_asset_key_with_lookup` touch: a data venue on an exchange no instrument executes on,
    /// a perpetual settled in an asset its underlying does not name, and a spec whose quantity is
    /// denominated in an asset only the spec names.
    fn serde_fixture() -> Vec<Instrument<ExchangeId, Asset>> {
        use crate::instrument::{
            data_venue::DataVenue,
            kind::perpetual::PerpetualContract,
            spec::{
                InstrumentSpec, InstrumentSpecNotional, InstrumentSpecPrice,
                InstrumentSpecQuantity, OrderQuantityUnits,
            },
        };

        let mut kraken_eth_usd = instrument(ExchangeId::Kraken, "eth", "usd");
        kraken_eth_usd.spec = Some(InstrumentSpec::new(
            InstrumentSpecPrice::new(Decimal::ONE, Decimal::ONE),
            InstrumentSpecQuantity::new(
                OrderQuantityUnits::Asset(Asset::new_from_exchange("eth_lot")),
                Decimal::ONE,
                Decimal::ONE,
            ),
            InstrumentSpecNotional::new(Decimal::ONE),
        ));

        vec![
            kraken_eth_usd,
            instrument(ExchangeId::BinanceSpot, "btc", "usdt"),
            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)),
            Instrument::new(
                ExchangeId::BinanceFuturesUsd,
                "binance_futures_usd-btc_usdt-perp",
                "BTCUSDT",
                Underlying::new(
                    Asset::new_from_exchange("btc"),
                    Asset::new_from_exchange("usdt"),
                ),
                InstrumentQuoteAsset::UnderlyingQuote,
                InstrumentKind::Perpetual(PerpetualContract {
                    contract_size: Decimal::ONE,
                    settlement_asset: Asset::new_from_exchange("usdc"),
                }),
                None,
            ),
        ]
    }

    #[test]
    fn test_serde_round_trip_reproduces_the_same_indices() {
        let indexed = IndexedInstruments::new(serde_fixture());

        let json = serde_json::to_string(&indexed).unwrap();
        let restored: IndexedInstruments = serde_json::from_str(&json).unwrap();

        assert_eq!(restored, indexed);
        // The spec-only asset is registered again on the way back in.
        assert!(
            restored
                .find_asset_index(ExchangeId::Kraken, &AssetNameInternal::from("eth_lot"))
                .is_ok()
        );
        // The data venue is indexed although no instrument executes on it.
        assert!(
            restored
                .exchanges()
                .iter()
                .any(|keyed| keyed.value == ExchangeId::LseEquities)
        );
    }

    #[test]
    fn test_serialises_as_the_plain_instrument_list() {
        let instruments = serde_fixture();
        let indexed = IndexedInstruments::new(instruments.clone());

        // Building sorts the instruments, so the list is written in index order.
        let mut expected = instruments;
        expected.sort();

        assert_eq!(
            serde_json::to_value(&indexed).unwrap(),
            serde_json::to_value(&expected).unwrap()
        );
    }

    #[test]
    fn test_deserialise_rejects_a_duplicate_name_internal() {
        let mut instruments = vec![
            instrument(ExchangeId::BinanceSpot, "btc", "usdt"),
            instrument(ExchangeId::BinanceSpot, "eth", "usdt"),
        ];
        instruments[1].name_internal = instruments[0].name_internal.clone();
        let json = serde_json::to_string(&instruments).unwrap();

        let err = serde_json::from_str::<IndexedInstruments>(&json)
            .unwrap_err()
            .to_string();
        assert!(err.contains("duplicate InstrumentNameInternal"), "{err}");
    }

    #[test]
    fn test_deserialise_rejects_a_non_positive_contract_size() {
        let mut instruments = serde_fixture();
        for instrument in &mut instruments {
            if let InstrumentKind::Perpetual(contract) = &mut instrument.kind {
                contract.contract_size = Decimal::ZERO;
            }
        }
        let json = serde_json::to_string(&instruments).unwrap();

        let err = serde_json::from_str::<IndexedInstruments>(&json)
            .unwrap_err()
            .to_string();
        assert!(err.contains("contract_size"), "{err}");
    }

    #[test]
    fn test_deserialise_rejects_the_former_index_bearing_format() {
        // The derive this replaced wrote the private index tables. That format can declare
        // indices that disagree with their positions, so it no longer loads at all.
        let json =
            r#"{"exchanges":[{"key":0,"value":"binance_spot"}],"assets":[],"instruments":[]}"#;
        assert!(serde_json::from_str::<IndexedInstruments>(json).is_err());
    }
}