rustrade-instrument 0.19.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
use crate::{
    Underlying,
    asset::Asset,
    instrument::{
        data_venue::DataVenue,
        kind::{
            InstrumentKind, cfd::CfdContract, future::FutureContract, option::OptionContract,
            perpetual::PerpetualContract,
        },
        market_data::{MarketDataInstrument, kind::MarketDataInstrumentKind},
        name::{InstrumentNameExchange, InstrumentNameInternal},
        quote::InstrumentQuoteAsset,
        spec::{InstrumentSpec, InstrumentSpecQuantity, OrderQuantityUnits},
    },
};
use derive_more::{Constructor, Display};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::fmt::Formatter;

/// Defines an [`Instrument`]s [`InstrumentKind`] (eg/ Spot, Perpetual, etc).
pub mod kind;

/// Defines the [`DataVenue`] an [`Instrument`]s market data is sourced from, when that differs
/// from the venue it is executed on.
pub mod data_venue;

/// Defines the [`InstrumentNameExchange`] and [`InstrumentNameExchange`] types, used as
/// `SmolStr` identifiers for an [`Instrument`].
pub mod name;

/// Defines the [`InstrumentSpec`], including specifications for an [`Instrument`]s
/// price, quantity and notional value.
///
/// eg/ `InstrumentSpecPrice.tick_size`, `OrderQuantityUnits`, etc.
pub mod spec;

/// Defines a simplified [`MarketDataInstrument`], with only the necessary data to subscribe to
/// market data feeds.
pub mod market_data;

/// Defines the [`InstrumentQuoteAsset`] (underlying base or quote) for an [`Instrument`].
pub mod quote;

/// Unique identifier for an `Instrument` traded on an execution.
///
/// Used to key data events in a memory efficient way.
#[derive(
    Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Display,
)]
pub struct InstrumentId(pub u64);

#[derive(
    Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Constructor,
)]
pub struct InstrumentIndex(pub usize);

impl InstrumentIndex {
    pub fn index(&self) -> usize {
        self.0
    }
}

impl std::fmt::Display for InstrumentIndex {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "InstrumentIndex({})", self.0)
    }
}

/// Comprehensive Instrument model, containing all the data required to subscribe to market data
/// and generate correct orders.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub struct Instrument<ExchangeKey, AssetKey> {
    pub exchange: ExchangeKey,
    pub name_internal: InstrumentNameInternal,
    pub name_exchange: InstrumentNameExchange,
    pub underlying: Underlying<AssetKey>,
    pub quote: InstrumentQuoteAsset,
    #[serde(alias = "instrument_kind")]
    pub kind: InstrumentKind<AssetKey>,
    pub spec: Option<InstrumentSpec<AssetKey>>,

    /// Venue this `Instrument`s **market data** is sourced from, when that differs from
    /// `exchange` — see [`DataVenue`], and read it via [`Self::data_exchange`] /
    /// [`Self::data_name_exchange`] so the fallback to `exchange`/`name_exchange` is applied in
    /// one place.
    ///
    /// Declared **last** by convention, not by necessity — worth stating precisely so a future
    /// maintainer does not infer a tighter constraint than exists. `Instrument` derives `Ord` and
    /// `IndexedInstrumentsBuilder` sorts the collection before assigning each `InstrumentIndex`, so
    /// field order is in principle part of how indices are numbered; this field is nonetheless
    /// unreachable as a sort key in both of the cases that matter. A collection whose instruments
    /// all carry `None` — every collection built before this field existed — compares `Equal` here
    /// wherever the field sits, so adding it renumbers nothing regardless of position. And
    /// `IndexedInstrumentsBuilder::try_build` rejects a duplicate `name_internal`, so in any
    /// collection that builds at all, `Ord` between two distinct instruments is already decided by
    /// an earlier field and never reaches this one to break a tie. Last is simply the least
    /// surprising place for it.
    ///
    /// `default = "Option::default"` rather than a bare `default`: the bare form makes serde infer
    /// an `ExchangeKey: Default` bound on the whole `Deserialize` impl, which `Keyed<ExchangeIndex,
    /// ExchangeId>` — the key every *indexed* `Instrument` carries — does not satisfy. Naming the
    /// path keeps the bound off.
    ///
    /// Enforced by the compiler rather than by a test: reverting to the bare form fails to *build*
    /// wherever an indexed `Instrument` is deserialised, so no runtime test below pins it.
    #[serde(default = "Option::default")]
    pub data_venue: Option<DataVenue<ExchangeKey>>,
}

impl<ExchangeKey, AssetKey> Instrument<ExchangeKey, AssetKey> {
    /// Construct a new `Instrument` with the provided data.
    ///
    /// This constructor assumes the [`InstrumentNameInternal`] can be constructed in the default
    /// style via the [`InstrumentNameInternal::new_from_exchange`] constructor.
    pub fn new<NameInternal, NameExchange>(
        exchange: ExchangeKey,
        name_internal: NameInternal,
        name_exchange: NameExchange,
        underlying: Underlying<AssetKey>,
        quote: InstrumentQuoteAsset,
        kind: InstrumentKind<AssetKey>,
        spec: Option<InstrumentSpec<AssetKey>>,
    ) -> Self
    where
        NameInternal: Into<InstrumentNameInternal>,
        NameExchange: Into<InstrumentNameExchange>,
    {
        Self {
            exchange,
            name_internal: name_internal.into(),
            name_exchange: name_exchange.into(),
            quote,
            underlying,
            kind,
            spec,
            data_venue: None,
        }
    }

    /// Construct a new `Spot` `Instrument` with the provided data.
    ///
    /// This constructor assumes the [`InstrumentNameInternal`] can be constructed in the default
    /// style via the [`InstrumentNameInternal::new_from_exchange`] constructor.
    pub fn spot<NameInternal, NameExchange>(
        exchange: ExchangeKey,
        name_internal: NameInternal,
        name_exchange: NameExchange,
        underlying: Underlying<AssetKey>,
        spec: Option<InstrumentSpec<AssetKey>>,
    ) -> Self
    where
        NameInternal: Into<InstrumentNameInternal>,
        NameExchange: Into<InstrumentNameExchange>,
    {
        Self {
            exchange,
            name_internal: name_internal.into(),
            name_exchange: name_exchange.into(),
            quote: InstrumentQuoteAsset::UnderlyingQuote,
            underlying,
            kind: InstrumentKind::Spot,
            spec,
            data_venue: None,
        }
    }

    /// Source this `Instrument`s market data from a different venue than it is executed on.
    ///
    /// See [`DataVenue`] for the fallback semantics and — importantly — the suitability obligation
    /// that comes with deciding on one venue's prices and filling on another.
    pub fn with_data_venue(mut self, data_venue: DataVenue<ExchangeKey>) -> Self {
        self.data_venue = Some(data_venue);
        self
    }

    /// Venue this `Instrument`s market data is sourced from.
    ///
    /// Falls back to `exchange` when no [`DataVenue`] is set, so this is the correct accessor for
    /// every instrument, single-venue or not.
    pub fn data_exchange(&self) -> &ExchangeKey {
        self.data_venue
            .as_ref()
            .map_or(&self.exchange, |data_venue| &data_venue.exchange)
    }

    /// Symbol the market data venue uses for this `Instrument`.
    ///
    /// Falls back to `name_exchange` when the data venue spells it the same way, or when there is
    /// no [`DataVenue`] at all.
    pub fn data_name_exchange(&self) -> &InstrumentNameExchange {
        self.data_venue
            .as_ref()
            .and_then(|data_venue| data_venue.name_exchange.as_ref())
            .unwrap_or(&self.name_exchange)
    }

    /// The step a position in this `Instrument`, and an order closing it, is sized in: the
    /// [`InstrumentSpec`]'s quantity increment, when the spec counts quantities in the unit a
    /// position is counted in. `None` otherwise.
    ///
    /// A position is counted in the base asset on [`InstrumentKind::Spot`], and in contracts on a
    /// derivative. So the spec's unit must be [`OrderQuantityUnits::Asset`] of the base asset on
    /// spot, and [`OrderQuantityUnits::Contract`] on a derivative. A derivative whose contract is
    /// one unit of its base (`contract_size` 1) accepts the base asset too, since the two units
    /// are then the same. A step in [`OrderQuantityUnits::Quote`], in another asset, or not above
    /// zero says nothing about a position's quantity, so it gives `None`, as no spec does.
    ///
    /// Round a quantity to it with [`round_toward_zero_to_step`].
    pub fn quantity_step(&self) -> Option<Decimal>
    where
        AssetKey: PartialEq,
    {
        let quantity = &self.spec.as_ref()?.quantity;
        let counts_positions = match (&self.kind, &quantity.unit) {
            (InstrumentKind::Spot, OrderQuantityUnits::Asset(asset)) => {
                *asset == self.underlying.base
            }
            (InstrumentKind::Spot, OrderQuantityUnits::Contract) => false,
            (_, OrderQuantityUnits::Contract) => true,
            (kind, OrderQuantityUnits::Asset(asset)) => {
                kind.contract_size() == Decimal::ONE && *asset == self.underlying.base
            }
            (_, OrderQuantityUnits::Quote) => false,
        };
        (counts_positions && quantity.increment > Decimal::ZERO).then_some(quantity.increment)
    }

    /// Map this Instruments `ExchangeKey` to a new key, using the provided lookup closure.
    ///
    /// The closure is applied to the execution `exchange` **and** to any [`DataVenue`]s exchange,
    /// which is why it takes a lookup rather than a single pre-resolved key: those are two
    /// different venues, so one key cannot serve both. A signature that accepted one key could
    /// only stamp the execution venue's key onto the data venue — silently pointing market-data
    /// state at the wrong exchange.
    pub fn map_exchange_key<FnFindExchange, NewExchangeKey>(
        self,
        find_exchange: FnFindExchange,
    ) -> Instrument<NewExchangeKey, AssetKey>
    where
        FnFindExchange: Fn(&ExchangeKey) -> NewExchangeKey,
    {
        let Instrument {
            exchange,
            name_internal,
            name_exchange,
            underlying,
            quote,
            kind,
            spec,
            data_venue,
        } = self;

        let data_venue =
            data_venue.map(|data_venue| data_venue.map_exchange_key(|key| find_exchange(key)));

        Instrument {
            exchange: find_exchange(&exchange),
            name_internal,
            name_exchange,
            underlying,
            quote,
            kind,
            spec,
            data_venue,
        }
    }

    /// Map this Instruments `AssetKey` to a new key, using the provided lookup closure.
    pub fn map_asset_key_with_lookup<FnFindAsset, NewAssetKey, Error>(
        self,
        find_asset: FnFindAsset,
    ) -> Result<Instrument<ExchangeKey, NewAssetKey>, Error>
    where
        FnFindAsset: Fn(&AssetKey) -> Result<NewAssetKey, Error>,
    {
        let Instrument {
            exchange,
            name_internal,
            name_exchange,
            underlying,
            quote,
            kind,
            spec,
            data_venue,
        } = self;

        let base_new_key = find_asset(&underlying.base)?;
        let quote_new_key = find_asset(&underlying.quote)?;

        let kind = match kind {
            InstrumentKind::Spot => InstrumentKind::Spot,
            InstrumentKind::Perpetual(contract) => InstrumentKind::Perpetual(PerpetualContract {
                contract_size: contract.contract_size,
                settlement_asset: find_asset(&contract.settlement_asset)?,
            }),
            InstrumentKind::Future(contract) => InstrumentKind::Future(FutureContract {
                contract_size: contract.contract_size,
                settlement_asset: find_asset(&contract.settlement_asset)?,
                expiry: contract.expiry,
            }),
            InstrumentKind::Option(contract) => InstrumentKind::Option(OptionContract {
                contract_size: contract.contract_size,
                settlement_asset: find_asset(&contract.settlement_asset)?,
                kind: contract.kind,
                exercise: contract.exercise,
                expiry: contract.expiry,
                strike: contract.strike,
            }),
            InstrumentKind::Cfd(contract) => InstrumentKind::Cfd(CfdContract {
                contract_size: contract.contract_size,
                settlement_asset: find_asset(&contract.settlement_asset)?,
            }),
        };

        let spec = match spec {
            Some(spec) => {
                let InstrumentSpec {
                    price,
                    quantity:
                        InstrumentSpecQuantity {
                            unit,
                            min,
                            increment,
                        },
                    notional,
                } = spec;

                let unit = match unit {
                    OrderQuantityUnits::Asset(asset) => {
                        OrderQuantityUnits::Asset(find_asset(&asset)?)
                    }
                    OrderQuantityUnits::Contract => OrderQuantityUnits::Contract,
                    OrderQuantityUnits::Quote => OrderQuantityUnits::Quote,
                };

                Some(InstrumentSpec {
                    price,
                    quantity: InstrumentSpecQuantity {
                        unit,
                        min,
                        increment,
                    },
                    notional,
                })
            }
            None => None,
        };

        Ok(Instrument {
            exchange,
            name_internal,
            name_exchange,
            underlying: Underlying::new(base_new_key, quote_new_key),
            quote,
            kind,
            spec,
            // The `DataVenue` holds no `AssetKey` — it names a venue and a symbol, and the
            // underlying assets are the instrument's own regardless of who prices it.
            data_venue,
        })
    }
}

/// `quantity` rounded toward zero to a whole multiple of `step`, on either side of zero. A
/// `step` not above zero leaves it as it is.
///
/// Toward zero shrinks a quantity's size whatever its sign, so a long and a short of the same size
/// round to the same size: `1.019` and `-1.019` in steps of `0.01` give `1.01` and `-1.01`.
pub fn round_toward_zero_to_step(quantity: Decimal, step: Decimal) -> Decimal {
    if step <= Decimal::ZERO {
        return quantity;
    }
    // `%` keeps the dividend's sign, so the remainder always lies between `quantity` and zero.
    quantity - quantity % step
}

impl<ExchangeKey> From<&Instrument<ExchangeKey, Asset>> for MarketDataInstrument {
    fn from(value: &Instrument<ExchangeKey, Asset>) -> Self {
        Self {
            base: value.underlying.base.name_internal.clone(),
            quote: value.underlying.quote.name_internal.clone(),
            kind: MarketDataInstrumentKind::from(&value.kind),
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)] // Test code: panics on bad input are acceptable
mod tests {
    use super::*;
    use crate::{
        exchange::ExchangeId,
        instrument::spec::{InstrumentSpecNotional, InstrumentSpecPrice},
    };
    use rust_decimal_macros::dec;

    /// An `AAPL` traded on one venue, optionally priced by another.
    fn instrument(data_venue: Option<DataVenue<ExchangeId>>) -> Instrument<ExchangeId, Asset> {
        let instrument = Instrument::spot(
            ExchangeId::AlpacaBroker,
            "alpaca_broker-aapl",
            "AAPL",
            Underlying::new(
                Asset::new_from_exchange("aapl"),
                Asset::new_from_exchange("usd"),
            ),
            None,
        );

        match data_venue {
            Some(data_venue) => instrument.with_data_venue(data_venue),
            None => instrument,
        }
    }

    /// `data_venue` is declared **last**, and that is load-bearing rather than stylistic:
    /// `Instrument` derives `Ord` from field order and `IndexedInstrumentsBuilder` sorts the
    /// collection before assigning each `InstrumentIndex`, so the field's *position* is part of how
    /// instruments are numbered. Move it above `spec` and this test fails while every existing
    /// collection silently renumbers — indices that are serialized into engine state, the audit
    /// replica and backtest replay streams.
    #[test]
    fn data_venue_sorts_last_so_it_renumbers_no_existing_collection() {
        // Identical up to `spec`, which is declared BEFORE `data_venue`. `Option: None < Some`, so
        // each field on its own would order these opposite ways: `spec` puts the specless
        // instrument first, `data_venue` puts the venueless one first. Only one of them can decide,
        // and it must be the earlier field.
        let no_spec_with_data_venue =
            instrument(Some(DataVenue::new_same_name(ExchangeId::LseEquities)));
        let mut spec_without_data_venue = instrument(None);
        spec_without_data_venue.spec = Some(InstrumentSpec::new(
            InstrumentSpecPrice::new(Decimal::ONE, Decimal::ONE),
            InstrumentSpecQuantity::new(OrderQuantityUnits::Quote, Decimal::ONE, Decimal::ONE),
            InstrumentSpecNotional::new(Decimal::ONE),
        ));

        assert!(
            no_spec_with_data_venue < spec_without_data_venue,
            "an earlier field must decide the order, whatever `data_venue` says"
        );

        // And among instruments equal in every earlier field, it is the tie-break — so declaring it
        // appends to the sort key rather than displacing any part of it.
        assert!(instrument(None) < no_spec_with_data_venue);
    }

    #[test]
    fn a_single_venue_instrument_reports_its_execution_venue_as_its_data_venue() {
        // The fallback is what lets every caller read `data_exchange()` unconditionally, rather
        // than each one re-deriving `data_venue.unwrap_or(exchange)` and one of them getting it
        // wrong.
        let instrument = instrument(None);

        assert_eq!(instrument.data_exchange(), &ExchangeId::AlpacaBroker);
        assert_eq!(
            instrument.data_name_exchange(),
            &InstrumentNameExchange::new("AAPL")
        );
    }

    #[test]
    fn a_data_venue_without_a_symbol_overrides_the_venue_but_keeps_the_execution_symbol() {
        // The common case: both venues spell it the same way, so only the venue is stated.
        let instrument = instrument(Some(DataVenue::new_same_name(ExchangeId::LseEquities)));

        assert_eq!(instrument.data_exchange(), &ExchangeId::LseEquities);
        assert_eq!(
            instrument.data_name_exchange(),
            &InstrumentNameExchange::new("AAPL")
        );
        // The execution side is untouched — this is one instrument on one ledger, not two.
        assert_eq!(instrument.exchange, ExchangeId::AlpacaBroker);
        assert_eq!(
            instrument.name_exchange,
            InstrumentNameExchange::new("AAPL")
        );
    }

    #[test]
    fn a_data_venue_symbol_overrides_the_execution_symbol() {
        // The case the field exists for: LSE quotes BP as `BP.L`, a US broker as `BP`. Subscribing
        // under the execution symbol would silently receive nothing, or another instrument's
        // prices.
        let instrument = instrument(Some(DataVenue::new(
            ExchangeId::LseEquities,
            Some(InstrumentNameExchange::new("BP.L")),
        )));

        assert_eq!(instrument.data_exchange(), &ExchangeId::LseEquities);
        assert_eq!(
            instrument.data_name_exchange(),
            &InstrumentNameExchange::new("BP.L")
        );
        assert_eq!(
            instrument.name_exchange,
            InstrumentNameExchange::new("AAPL")
        );
    }

    #[test]
    fn map_exchange_key_maps_the_data_venue_too() {
        // The whole reason `map_exchange_key` takes a lookup rather than one pre-resolved key: the
        // two venues are different exchanges, so a single key cannot serve both. Were the data
        // venue left unmapped (or stamped with the execution venue's key), market-data state would
        // point at the wrong exchange with nothing to signal it.
        let instrument = instrument(Some(DataVenue::new(
            ExchangeId::LseEquities,
            Some(InstrumentNameExchange::new("BP.L")),
        )));

        let mapped = instrument.map_exchange_key(|exchange| exchange.as_str().to_owned());

        assert_eq!(mapped.exchange, "alpaca_broker");
        assert_eq!(
            mapped
                .data_venue
                .as_ref()
                .map(|venue| venue.exchange.as_str()),
            Some("lse_equities")
        );
        // The symbol rides along unchanged — only the key is mapped.
        assert_eq!(
            mapped.data_name_exchange(),
            &InstrumentNameExchange::new("BP.L")
        );
    }

    #[test]
    fn an_instrument_without_a_data_venue_deserialises_from_a_config_that_predates_the_field() {
        // `data_venue` is additive, so every config written before it existed must still load. If
        // this breaks, the field is a breaking change to on-disk configs rather than to source.
        let json = r#"{
            "exchange": "binance_spot",
            "name_internal": "binance_spot-btc_usdt",
            "name_exchange": "BTCUSDT",
            "underlying": {
                "base": { "name_internal": "btc", "name_exchange": "BTC" },
                "quote": { "name_internal": "usdt", "name_exchange": "USDT" }
            },
            "quote": "underlying_quote",
            "kind": "spot",
            "spec": null
        }"#;

        let instrument =
            serde_json::from_str::<Instrument<ExchangeId, Asset>>(json).expect("must deserialise");

        assert_eq!(instrument.data_venue, None);
        assert_eq!(instrument.data_exchange(), &ExchangeId::BinanceSpot);
    }

    #[test]
    fn a_data_venue_round_trips_through_serde() {
        let instrument = instrument(Some(DataVenue::new(
            ExchangeId::LseEquities,
            Some(InstrumentNameExchange::new("BP.L")),
        )));

        let json = serde_json::to_string(&instrument).expect("must serialise");
        let round_tripped =
            serde_json::from_str::<Instrument<ExchangeId, Asset>>(&json).expect("must deserialise");

        assert_eq!(round_tripped, instrument);
    }

    /// `instrument(None)` with a spec whose quantity is counted in `unit` in steps of `increment`.
    fn with_quantity_spec(
        mut instrument: Instrument<ExchangeId, Asset>,
        unit: OrderQuantityUnits<Asset>,
        increment: Decimal,
    ) -> Instrument<ExchangeId, Asset> {
        instrument.spec = Some(InstrumentSpec::new(
            InstrumentSpecPrice::new(dec!(0.01), dec!(0.01)),
            InstrumentSpecQuantity::new(unit, increment, increment),
            InstrumentSpecNotional::new(Decimal::ONE),
        ));
        instrument
    }

    /// `instrument(None)` as a perpetual of `contract_size` base units per contract.
    fn perpetual(contract_size: Decimal) -> Instrument<ExchangeId, Asset> {
        let mut instrument = instrument(None);
        instrument.kind = InstrumentKind::Perpetual(PerpetualContract {
            contract_size,
            settlement_asset: Asset::new_from_exchange("usd"),
        });
        instrument
    }

    #[test]
    fn quantity_step_is_the_spot_increment_in_the_base_asset() {
        let aapl = Asset::new_from_exchange("aapl");
        let spot = with_quantity_spec(
            instrument(None),
            OrderQuantityUnits::Asset(aapl),
            dec!(0.01),
        );

        assert_eq!(spot.quantity_step(), Some(dec!(0.01)));
    }

    #[test]
    fn quantity_step_is_none_without_a_spec() {
        assert_eq!(instrument(None).quantity_step(), None);
    }

    #[test]
    fn quantity_step_is_none_when_the_spec_is_not_in_the_unit_a_position_is_counted_in() {
        let base = || OrderQuantityUnits::Asset(Asset::new_from_exchange("aapl"));
        let other = OrderQuantityUnits::Asset(Asset::new_from_exchange("aapl_lot"));
        let cases = [
            ("spot in quote", instrument(None), OrderQuantityUnits::Quote),
            ("spot in another asset", instrument(None), other),
            (
                "spot in contracts",
                instrument(None),
                OrderQuantityUnits::Contract,
            ),
            (
                "perpetual in quote",
                perpetual(Decimal::ONE),
                OrderQuantityUnits::Quote,
            ),
            ("perpetual of 100 in base", perpetual(dec!(100)), base()),
        ];

        for (case, instrument, unit) in cases {
            let instrument = with_quantity_spec(instrument, unit, dec!(0.01));
            assert_eq!(instrument.quantity_step(), None, "{case}");
        }
    }

    #[test]
    fn quantity_step_of_a_derivative_is_in_contracts_or_a_one_unit_contract_s_base() {
        let in_contracts = with_quantity_spec(
            perpetual(dec!(100)),
            OrderQuantityUnits::Contract,
            Decimal::ONE,
        );
        let in_base = with_quantity_spec(
            perpetual(Decimal::ONE),
            OrderQuantityUnits::Asset(Asset::new_from_exchange("aapl")),
            dec!(0.001),
        );

        assert_eq!(in_contracts.quantity_step(), Some(Decimal::ONE));
        assert_eq!(in_base.quantity_step(), Some(dec!(0.001)));
    }

    #[test]
    fn quantity_step_is_none_unless_the_increment_is_above_zero() {
        let aapl = || OrderQuantityUnits::Asset(Asset::new_from_exchange("aapl"));

        for increment in [Decimal::ZERO, dec!(-0.01)] {
            let instrument = with_quantity_spec(instrument(None), aapl(), increment);
            assert_eq!(instrument.quantity_step(), None, "increment {increment}");
        }
    }

    #[test]
    fn round_toward_zero_to_step_shrinks_either_sign_to_a_whole_step() {
        let cases = [
            (dec!(1.019), dec!(1.01)),
            (dec!(-1.019), dec!(-1.01)),
            (dec!(1.01), dec!(1.01)),
            (dec!(0.009), Decimal::ZERO),
            (dec!(-0.009), Decimal::ZERO),
            (Decimal::ZERO, Decimal::ZERO),
        ];

        for (quantity, rounded) in cases {
            assert_eq!(
                round_toward_zero_to_step(quantity, dec!(0.01)),
                rounded,
                "{quantity}"
            );
        }
    }

    #[test]
    fn round_toward_zero_to_step_leaves_the_quantity_unless_the_step_is_above_zero() {
        for step in [Decimal::ZERO, dec!(-0.01)] {
            assert_eq!(
                round_toward_zero_to_step(dec!(1.019), step),
                dec!(1.019),
                "step {step}"
            );
        }
    }
}