rustrade-instrument 0.1.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
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};

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.
#[derive(Debug, Clone, PartialEq, PartialOrd, Deserialize, Serialize)]
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`].
    pub fn new<Iter, I>(instruments: Iter) -> Self
    where
        Iter: IntoIterator<Item = I>,
        I: Into<Instrument<ExchangeId, Asset>>,
    {
        instruments
            .into_iter()
            .fold(Self::builder(), |builder, instrument| {
                builder.add_instrument(instrument.into())
            })
            .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(AssetIndex)` - instrument found.
    /// * `Err(IndexError)` - 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(IndexError::AssetIndex(format!(
                "Asset: ({}, {}) is not present in indexed instrument assets: {:?}",
                exchange, name, self.assets
            )))
    }

    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<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},
    };

    #[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),
                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::AssetIndex(_)));

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

    #[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);
    }
}