rustrade-execution 0.16.0

Stream private account data from financial venues, and execute (live or mock) orders.
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
use rust_decimal::Decimal;
use rustrade_instrument::asset::name::AssetNameExchange;
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Which side of the trade a fill was on: the one that supplied liquidity, or the one that took it.
///
/// Venues price these differently, and usually by a wide margin — a maker rebate against a taker
/// fee is the whole economics of quoting. A fee model that cannot tell them apart charges the taker
/// rate for everything, which systematically overstates the cost of exactly the strategies that
/// rest orders in order to earn the maker side.
#[derive(
    Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Deserialize, Serialize,
)]
pub enum Liquidity {
    /// The fill took liquidity already resting on the book: a market order, or a limit order
    /// marketable on arrival. The default, because it is the conservative assumption — a model that
    /// guesses wrong this way overstates costs rather than inventing profit.
    #[default]
    Taker,
    /// The fill supplied liquidity: an order that rested on the book and was matched by someone
    /// else's incoming order.
    Maker,
}

/// Computes the trading fee for a single fill.
///
/// # Arguments
/// * `price` - Execution price per unit of the underlying.
/// * `quantity` - Number of contracts (or shares/units) filled.
/// * `contract_size` - Multiplier converting contracts to underlying units
///   (e.g. 100 for standard equity options). Use `Decimal::ONE` for spot.
/// * `liquidity` - Whether the fill made or took liquidity; see [`Liquidity`].
pub trait FeeModel {
    fn compute_fee(
        &self,
        price: Decimal,
        quantity: Decimal,
        contract_size: Decimal,
        liquidity: Liquidity,
    ) -> Decimal;
}

/// Zero-fee model. Useful for backtests where fees are excluded.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Deserialize, Serialize,
)]
pub struct ZeroFeeModel;

impl FeeModel for ZeroFeeModel {
    fn compute_fee(
        &self,
        _price: Decimal,
        _quantity: Decimal,
        _contract_size: Decimal,
        _liquidity: Liquidity,
    ) -> Decimal {
        Decimal::ZERO
    }
}

/// Flat commission charged per contract filled.
///
/// `total_fee = commission_per_contract * quantity.abs()`
///
/// This matches the typical Alpaca/IBKR per-contract options pricing.
/// `contract_size` is accepted but not used; the fee is per contract unit,
/// not per underlying share.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub struct PerContractFeeModel {
    #[serde(with = "rust_decimal::serde::str")]
    pub commission_per_contract: Decimal,
}

impl FeeModel for PerContractFeeModel {
    /// `liquidity` is ignored: a per-contract commission is a flat brokerage charge, and the
    /// brokers this models (Alpaca, IBKR options) do not vary it by who supplied liquidity.
    fn compute_fee(
        &self,
        _price: Decimal,
        quantity: Decimal,
        _contract_size: Decimal,
        _liquidity: Liquidity,
    ) -> Decimal {
        self.commission_per_contract * quantity.abs()
    }
}

/// Percentage-of-notional fee model for spot, futures and CFD exchanges.
///
/// `total_fee = rate * price * quantity.abs() * contract_size`
///
/// Common for crypto spot/futures exchanges (e.g. Binance 0.1% taker fee).
///
/// # Why `contract_size` is applied
///
/// The notional a percentage is charged on is the *underlying* exposure, not the contract count.
/// For `Spot` the multiplier is `Decimal::ONE` and the term is inert, but a €25-per-point index
/// CFD at 5000 has a notional of €125,000, not €5,000 — dropping the multiplier would understate
/// the fee by exactly that factor, silently, on every fill. The same applies to any `Future` or
/// `Perpetual` whose `contract_size` is not one.
///
/// Contrast [`PerContractFeeModel`], which ignores the multiplier because its fee genuinely is
/// per contract rather than per underlying unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub struct PercentageFeeModel {
    /// Fee rate charged when the fill **took** liquidity, and when no [`maker_rate`](Self::maker_rate)
    /// is configured. Typical range is `[0, 1]`:
    /// - `0.001` = 0.1% (common taker fee)
    /// - `0.0005` = 0.05% (common maker fee)
    ///
    /// No validation is performed; values outside `[0, 1]` are accepted
    /// but produce unusual fee amounts.
    #[serde(with = "rust_decimal::serde::str")]
    pub rate: Decimal,

    /// Fee rate charged when the fill **made** liquidity. `None` charges [`rate`](Self::rate) on
    /// both sides.
    ///
    /// Absent by default so a configuration written before this field existed deserialises and
    /// prices exactly as it did. Set it to model a venue's maker schedule — commonly a fraction of
    /// the taker rate, and on some venues a rebate, which this represents as a negative rate.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "rust_decimal::serde::str_option"
    )]
    pub maker_rate: Option<Decimal>,
}

impl PercentageFeeModel {
    /// One rate, charged on both sides of the book.
    pub fn new(rate: Decimal) -> Self {
        Self {
            rate,
            maker_rate: None,
        }
    }

    /// Distinct maker and taker rates, as a venue's fee schedule quotes them.
    ///
    /// A maker *rebate* is a negative `maker_rate`.
    pub fn maker_taker(maker_rate: Decimal, taker_rate: Decimal) -> Self {
        Self {
            rate: taker_rate,
            maker_rate: Some(maker_rate),
        }
    }

    /// The rate charged for `liquidity`: [`maker_rate`](Self::maker_rate) when it is configured and
    /// the fill made liquidity, otherwise [`rate`](Self::rate).
    pub fn rate_for(&self, liquidity: Liquidity) -> Decimal {
        match liquidity {
            Liquidity::Maker => self.maker_rate.unwrap_or(self.rate),
            Liquidity::Taker => self.rate,
        }
    }
}

impl FeeModel for PercentageFeeModel {
    fn compute_fee(
        &self,
        price: Decimal,
        quantity: Decimal,
        contract_size: Decimal,
        liquidity: Liquidity,
    ) -> Decimal {
        self.rate_for(liquidity) * price * quantity.abs() * contract_size
    }
}

/// Enum-dispatched fee model for use in types that require `Clone`, `PartialEq`,
/// `Serialize`, and `Deserialize` (e.g. `InstrumentState`).
///
/// Prefer this over `Box<dyn FeeModel>` when the field must be part of a derived
/// `serde` struct. Defaults to [`ZeroFeeModel`].
///
/// # Double-counting warning
///
/// Only enable a non-[`Zero`](FeeModelConfig::Zero) fee model when the `ExecutionClient`
/// reports `Trade.fees.fees = 0` for fills (i.e., commission is not already embedded in
/// fill reports). If the client already includes fees in `fees.fees` and a fee model
/// is also active, fees will be counted twice.
///
/// # Variants
///
/// - [`Zero`](FeeModelConfig::Zero): No fees (backtests where fees are excluded).
/// - [`PerContract`](FeeModelConfig::PerContract): Flat per-contract commission (options).
/// - [`Percentage`](FeeModelConfig::Percentage): Percentage of notional (spot/futures).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub enum FeeModelConfig {
    Zero(ZeroFeeModel),
    PerContract(PerContractFeeModel),
    Percentage(PercentageFeeModel),
}

impl Default for FeeModelConfig {
    fn default() -> Self {
        Self::Zero(ZeroFeeModel)
    }
}

/// Which asset the simulated venue charges a spot fill's fee in.
///
/// The amount always comes from the venue's [`FeeModelConfig`], which prices a fee in quote. This
/// rule says only which balance it is taken from, so it changes no cost, only which asset pays it:
///
/// | Rule | Buy | Sell |
/// |---|---|---|
/// | [`Quote`](Self::Quote) | quote, on top of the notional | quote, out of the proceeds |
/// | [`Received`](Self::Received) | base, out of the quantity received | quote, out of the proceeds |
///
/// A fee in base is the quote fee divided by the fill price, to `Decimal`'s 28 digits. The fill
/// reports it in base, with that quote fee as its
/// [`AssetFees::fees_quote`](crate::trade::AssetFees::fees_quote).
///
/// Venues differ, and so do accounts on one venue. `Quote` matches Coinbase spot's default.
/// `Received` matches Binance spot's default, with BNB fee payment turned off. Pick the rule of
/// the account a backtest stands in for. A CFD fill is cash-settled, so its fee is always in
/// quote, whatever this says.
///
/// # A buy's fee in base
/// Under `Received`, a buy receives its quantity less the fee, and the engine nets a base fee from
/// a spot position (see `rustrade`'s `InstrumentState::update_from_trade`), so the two stay equal.
/// The holding is then not a round number: a buy of 1 with a 0.1 % fee holds 0.999. A live venue
/// sells only whole multiples of its lot step, so when the instrument's spec gives a quantity
/// step, the engine rounds the position toward zero to it and leaves the remainder in the balance,
/// where only the venue's own dust conversion can clear it. This venue has no lot step: it fills
/// whatever quantity it is sent, so a close of the rounded position leaves the same remainder
/// here as live.
///
/// A flat fee on a tiny buy can exceed the quantity it receives. The excess is then taken from the
/// base balance, and the order is refused if that cannot cover it, as a sell whose fee exceeds its
/// proceeds takes the excess from quote. A fill at a price that is not positive cannot be
/// converted, so it is charged in quote under either rule.
///
/// A fee charged in a third asset, such as BNB, is set apart from this rule, by
/// [`FeeAssetConfig`]. Where it does not apply, this rule does.
///
/// `#[non_exhaustive]`: further rules may be added.
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize,
)]
#[non_exhaustive]
pub enum SpotFeeAsset {
    /// The fee is in quote on both sides: on top of what a buy pays, and out of what a sell
    /// receives. Venue-neutral, and the base a fill moves is exactly its quantity.
    #[default]
    Quote,
    /// The fee is in the asset the fill receives: base out of a buy's quantity, quote out of a
    /// sell's proceeds.
    Received,
}

/// A third asset the simulated venue charges spot fees in, at a discount, while the account
/// holds enough of it: Binance's "pay fees with BNB".
///
/// # What a fill pays
/// The fee is the [`FeeModelConfig`]'s fee in quote, less [`discount`](Self::discount), converted
/// to the fee asset at the venue's price for it: the mid, else the last price, of a spot
/// instrument on the venue pairing the fee asset with the fill's quote asset, in either direction
/// (`BNB/USDT`, or the reciprocal of `USDT/BNB`). Of several, the one first by name. It is taken
/// from the fee asset's free balance when the fill settles, apart from what the fill exchanges,
/// and the fill reports it in the fee asset, as a live venue does. Nothing is reserved for it
/// while an order rests, since a venue does not hold the fee asset for open orders.
///
/// The fee is not rounded to the fee asset's precision, which this venue does not know, so it
/// can differ from a live venue's in its last decimals.
///
/// # When it falls back
/// The fill is charged as without this setting, the undiscounted fee under the venue's
/// [`SpotFeeAsset`] rule, when any of these holds:
/// - the fee asset's free balance is short of the fee: the whole fee falls back, none of it is
///   split. A margin account does not lend the fee asset for a fee.
/// - the venue holds no positive price for the fee asset in the fill's quote. A venue with no
///   market feed holds none.
/// - the instrument is the fee asset's own, its base or its quote (`BNB/USDT`, `ETH/BNB`). A live
///   venue discounts those too; this one does not.
/// - the fill is cash-settled (a CFD), or its fee is zero or negative.
///
/// A fill's fee asset says which happened. With an engine that prices the fee asset, PnL counts a
/// fee charged in it; otherwise a backtest leaves it out, as a live run does.
///
/// [`new`](Self::new) refuses a discount outside zero to one, and so does deserialising one.
/// Serialised, the discount is a decimal string (`"0.25"`).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(try_from = "FeeAssetRepr", into = "FeeAssetRepr")]
pub struct FeeAssetConfig(FeeAssetRepr);

/// The serialised form of a [`FeeAssetConfig`], before validation.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
struct FeeAssetRepr {
    asset: AssetNameExchange,
    #[serde(with = "rust_decimal::serde::str")]
    discount: Decimal,
}

impl FeeAssetConfig {
    /// Fees charged in `asset`, at `discount` off the fee model's fee: `0.25` for a quarter off.
    ///
    /// # Errors
    /// Returns [`FeeAssetConfigError`] if `discount` is below zero or above one.
    pub fn new(asset: AssetNameExchange, discount: Decimal) -> Result<Self, FeeAssetConfigError> {
        Self::try_from(FeeAssetRepr { asset, discount })
    }

    /// The asset fees are charged in.
    pub fn asset(&self) -> &AssetNameExchange {
        &self.0.asset
    }

    /// The fraction taken off the fee model's fee: zero for none, one for no fee at all.
    pub fn discount(&self) -> Decimal {
        self.0.discount
    }
}

impl TryFrom<FeeAssetRepr> for FeeAssetConfig {
    type Error = FeeAssetConfigError;

    fn try_from(repr: FeeAssetRepr) -> Result<Self, Self::Error> {
        if repr.discount < Decimal::ZERO || repr.discount > Decimal::ONE {
            return Err(FeeAssetConfigError::DiscountOutOfRange(repr.discount));
        }
        Ok(Self(repr))
    }
}

impl From<FeeAssetConfig> for FeeAssetRepr {
    fn from(config: FeeAssetConfig) -> Self {
        config.0
    }
}

/// Why a [`FeeAssetConfig`] was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum FeeAssetConfigError {
    /// A discount below zero, which would charge more than the fee model, or above one, which
    /// would pay the account for trading.
    #[error("fee asset discount {0} is outside 0 to 1")]
    DiscountOutOfRange(Decimal),
}

impl FeeModel for FeeModelConfig {
    fn compute_fee(
        &self,
        price: Decimal,
        quantity: Decimal,
        contract_size: Decimal,
        liquidity: Liquidity,
    ) -> Decimal {
        match self {
            FeeModelConfig::Zero(model) => {
                model.compute_fee(price, quantity, contract_size, liquidity)
            }
            FeeModelConfig::PerContract(model) => {
                model.compute_fee(price, quantity, contract_size, liquidity)
            }
            FeeModelConfig::Percentage(model) => {
                model.compute_fee(price, quantity, contract_size, liquidity)
            }
        }
    }
}

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

    fn d(s: &str) -> Decimal {
        s.parse().unwrap()
    }

    #[test]
    fn zero_fee_model_always_returns_zero() {
        assert_eq!(
            ZeroFeeModel.compute_fee(d("100"), d("5"), d("100"), Liquidity::Taker),
            Decimal::ZERO
        );
        assert_eq!(
            ZeroFeeModel.compute_fee(Decimal::ZERO, Decimal::ZERO, Decimal::ONE, Liquidity::Taker),
            Decimal::ZERO
        );
    }

    #[test]
    fn per_contract_fee_charges_by_quantity() {
        let model = PerContractFeeModel {
            commission_per_contract: d("0.65"),
        };
        assert_eq!(
            model.compute_fee(d("100"), d("10"), d("100"), Liquidity::Taker),
            d("6.5")
        );
    }

    #[test]
    fn per_contract_fee_uses_abs_quantity() {
        let model = PerContractFeeModel {
            commission_per_contract: d("0.65"),
        };
        // Negative quantity (sell side) should produce the same fee as positive.
        assert_eq!(
            model.compute_fee(d("100"), d("-10"), d("100"), Liquidity::Taker),
            model.compute_fee(d("100"), d("10"), d("100"), Liquidity::Taker),
        );
    }

    // --- FeeModelConfig enum dispatch ---

    #[test]
    fn fee_model_config_zero_dispatches() {
        let cfg = FeeModelConfig::Zero(ZeroFeeModel);
        assert_eq!(
            cfg.compute_fee(d("100"), d("5"), d("100"), Liquidity::Taker),
            Decimal::ZERO
        );
    }

    #[test]
    fn fee_model_config_per_contract_dispatches() {
        let model = PerContractFeeModel {
            commission_per_contract: d("0.65"),
        };
        let cfg = FeeModelConfig::PerContract(model);
        assert_eq!(
            cfg.compute_fee(d("100"), d("10"), d("100"), Liquidity::Taker),
            model.compute_fee(d("100"), d("10"), d("100"), Liquidity::Taker),
        );
    }

    #[test]
    fn fee_model_config_default_is_zero() {
        assert_eq!(
            FeeModelConfig::default(),
            FeeModelConfig::Zero(ZeroFeeModel)
        );
    }

    // --- PercentageFeeModel ---

    #[test]
    fn percentage_fee_computes_rate_times_notional() {
        // 0.1% fee rate
        let model = PercentageFeeModel::new(d("0.001"));
        // 10 units at price 100 = notional 1000, fee = 1000 * 0.001 = 1
        assert_eq!(
            model.compute_fee(d("100"), d("10"), d("1"), Liquidity::Taker),
            d("1")
        );
    }

    #[test]
    fn percentage_fee_uses_abs_quantity() {
        let model = PercentageFeeModel::new(d("0.001"));
        assert_eq!(
            model.compute_fee(d("100"), d("-10"), d("1"), Liquidity::Taker),
            model.compute_fee(d("100"), d("10"), d("1"), Liquidity::Taker),
        );
    }

    #[test]
    fn percentage_fee_scales_by_contract_size() {
        // A EUR25-per-point index CFD at 5000: the notional is 125_000, not 5_000, so 0.1% is 125.
        // Charging 5 here would understate every CFD fill by the multiplier.
        let model = PercentageFeeModel::new(d("0.001"));
        assert_eq!(
            model.compute_fee(d("5000"), d("1"), d("25"), Liquidity::Taker),
            d("125")
        );
    }

    #[test]
    fn percentage_fee_is_unchanged_for_a_unit_contract_size() {
        // Spot is the overwhelmingly common case and must be untouched by the multiplier.
        let model = PercentageFeeModel::new(d("0.001"));
        assert_eq!(
            model.compute_fee(d("100"), d("10"), Decimal::ONE, Liquidity::Taker),
            d("1")
        );
    }

    #[test]
    fn per_contract_fee_ignores_contract_size() {
        // The counterpart to `percentage_fee_scales_by_contract_size`: this fee genuinely is per
        // contract, so the multiplier must NOT apply. Pinned so the two models cannot drift into
        // sharing one rule.
        let model = PerContractFeeModel {
            commission_per_contract: d("0.65"),
        };
        assert_eq!(
            model.compute_fee(d("5000"), d("10"), d("25"), Liquidity::Taker),
            model.compute_fee(d("5000"), d("10"), Decimal::ONE, Liquidity::Taker),
        );
    }

    #[test]
    fn fee_model_config_percentage_dispatches() {
        let model = PercentageFeeModel::new(d("0.001"));
        let cfg = FeeModelConfig::Percentage(model);
        assert_eq!(
            cfg.compute_fee(d("100"), d("10"), d("1"), Liquidity::Taker),
            model.compute_fee(d("100"), d("10"), d("1"), Liquidity::Taker),
        );
    }

    // --- Serde round-trip tests ---

    #[test]
    fn zero_fee_model_serde_roundtrip() {
        let cfg = FeeModelConfig::Zero(ZeroFeeModel);
        let json = serde_json::to_string(&cfg).unwrap();
        assert_eq!(json, r#"{"Zero":null}"#);
        let parsed: FeeModelConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, cfg);
    }

    #[test]
    fn fee_model_config_default_when_field_omitted() {
        // Simulates deserializing a struct where fee_model field is absent
        #[derive(Deserialize)]
        struct Wrapper {
            #[serde(default)]
            fee_model: FeeModelConfig,
        }
        let parsed: Wrapper = serde_json::from_str(r#"{}"#).unwrap();
        assert_eq!(parsed.fee_model, FeeModelConfig::Zero(ZeroFeeModel));
    }

    #[test]
    fn percentage_fee_model_serde_roundtrip() {
        let cfg = FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001")));
        let json = serde_json::to_string(&cfg).unwrap();
        assert_eq!(json, r#"{"Percentage":{"rate":"0.001"}}"#);
        let parsed: FeeModelConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, cfg);
    }

    #[test]
    fn per_contract_fee_model_serde_roundtrip() {
        let cfg = FeeModelConfig::PerContract(PerContractFeeModel {
            commission_per_contract: d("0.65"),
        });
        let json = serde_json::to_string(&cfg).unwrap();
        assert_eq!(
            json,
            r#"{"PerContract":{"commission_per_contract":"0.65"}}"#
        );
        let parsed: FeeModelConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, cfg);
    }

    // --- Maker / taker ---

    #[test]
    fn a_percentage_model_without_a_maker_rate_charges_one_rate_on_both_sides() {
        let model = PercentageFeeModel::new(d("0.001"));

        assert_eq!(
            model.compute_fee(d("100"), d("10"), Decimal::ONE, Liquidity::Maker),
            model.compute_fee(d("100"), d("10"), Decimal::ONE, Liquidity::Taker),
            "an unconfigured maker rate must price exactly as the model did before the field \
             existed"
        );
    }

    #[test]
    fn a_configured_maker_rate_is_charged_only_to_the_maker() {
        let model = PercentageFeeModel::maker_taker(d("0.0002"), d("0.001"));

        assert_eq!(
            model.compute_fee(d("100"), d("10"), Decimal::ONE, Liquidity::Taker),
            d("1"),
            "0.1% of 1000 notional"
        );
        assert_eq!(
            model.compute_fee(d("100"), d("10"), Decimal::ONE, Liquidity::Maker),
            d("0.2"),
            "0.02% of 1000 notional"
        );
    }

    /// Some venues pay for liquidity. A rebate is a negative fee, not a missing one.
    #[test]
    fn a_maker_rebate_is_a_negative_fee() {
        let model = PercentageFeeModel::maker_taker(d("-0.0001"), d("0.001"));

        assert_eq!(
            model.compute_fee(d("100"), d("10"), Decimal::ONE, Liquidity::Maker),
            d("-0.1")
        );
    }

    #[test]
    fn a_per_contract_commission_does_not_vary_with_liquidity() {
        let model = PerContractFeeModel {
            commission_per_contract: d("0.65"),
        };

        assert_eq!(
            model.compute_fee(d("100"), d("10"), d("100"), Liquidity::Maker),
            model.compute_fee(d("100"), d("10"), d("100"), Liquidity::Taker)
        );
    }

    /// A config written before `maker_rate` existed must still deserialise, and price as it did.
    #[test]
    fn a_percentage_model_deserialises_without_a_maker_rate() {
        let model: PercentageFeeModel =
            serde_json::from_str(r#"{"rate":"0.001"}"#).expect("legacy shape must parse");

        assert_eq!(model, PercentageFeeModel::new(d("0.001")));
        assert_eq!(model.maker_rate, None);
    }

    #[test]
    fn a_percentage_model_round_trips_a_maker_rate() {
        let model = PercentageFeeModel::maker_taker(d("0.0002"), d("0.001"));
        let json = serde_json::to_string(&model).expect("must serialise");

        assert_eq!(
            serde_json::from_str::<PercentageFeeModel>(&json).expect("must round-trip"),
            model
        );
    }

    #[test]
    fn a_fee_asset_discount_must_lie_between_zero_and_one() {
        let bnb = || AssetNameExchange::new("BNB");
        for discount in ["0", "0.25", "1"] {
            let config = FeeAssetConfig::new(bnb(), d(discount)).unwrap();
            assert_eq!((config.asset(), config.discount()), (&bnb(), d(discount)));
        }
        for discount in ["-0.01", "1.01"] {
            assert_eq!(
                FeeAssetConfig::new(bnb(), d(discount)),
                Err(FeeAssetConfigError::DiscountOutOfRange(d(discount)))
            );
        }
    }

    /// The discount serialises as a decimal string, and deserialising refuses one out of range.
    #[test]
    fn a_fee_asset_config_round_trips_and_refuses_an_invalid_discount() {
        let config = FeeAssetConfig::new(AssetNameExchange::new("BNB"), d("0.25")).unwrap();
        let json = serde_json::to_string(&config).unwrap();
        assert_eq!(json, r#"{"asset":"BNB","discount":"0.25"}"#);
        assert_eq!(
            serde_json::from_str::<FeeAssetConfig>(&json).unwrap(),
            config
        );

        let error = serde_json::from_str::<FeeAssetConfig>(r#"{"asset":"BNB","discount":"2"}"#)
            .unwrap_err();
        assert!(error.to_string().contains("outside 0 to 1"), "{error}");
    }
}