openpit 0.5.0

Embeddable pre-trade risk SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
// Copyright The Pit Project Owners. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Please see https://openpit.dev and the OWNERS file for details.

//! Market-data wiring and runtime settings for
//! [`SpotFundsPolicy`](super::SpotFundsPolicy).
//!
//! The slippage / pricing-source / override cascade is runtime-updatable and
//! lives in [`SpotFundsSettings`], stored behind the policy's settings cell.
//! The market-data service handle in [`SpotFundsMarketData`] is fixed for the
//! policy's lifetime and is *not* part of the settings.

use std::collections::HashMap;
use std::fmt::{Display, Formatter};

use crate::core::instrument::Instrument;
use crate::marketdata::{
    AccountInfo, InstrumentId, MarketDataService, MarketDataSync, Quote, QuoteResolution,
};
use crate::param::{AccountGroupId, AccountId, Price};

use super::market_order_pricer::WithSlippage;

/// Upper bound (inclusive) on any slippage value, in basis points.
const MAX_SLIPPAGE_BPS: u16 = 10_000;

// ─── SpotFundsConfigError ─────────────────────────────────────────────────────

/// Error returned when building or updating [`SpotFundsSettings`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SpotFundsConfigError {
    /// The slippage value is out of the accepted range (0..=10 000 bps).
    SlippageOutOfRange {
        /// The bps value that triggered the error.
        bps: u16,
    },
}

impl Display for SpotFundsConfigError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SlippageOutOfRange { bps } => {
                write!(
                    f,
                    "slippage {bps} bps is out of range (must be <= 10 000 bps)"
                )
            }
        }
    }
}

impl std::error::Error for SpotFundsConfigError {}

/// Validates a slippage value against the accepted range.
fn check_slippage_bps(bps: u16) -> Result<(), SpotFundsConfigError> {
    if bps > MAX_SLIPPAGE_BPS {
        return Err(SpotFundsConfigError::SlippageOutOfRange { bps });
    }
    Ok(())
}

// ─── SpotFundsPriceError ──────────────────────────────────────────────────────

/// Error returned by the effective-price helpers on
/// [`SpotFundsMarketData`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SpotFundsPriceError {
    /// No usable quote is available for the instrument.
    QuoteUnavailable,
    /// The effective price could not be computed (decimal overflow or
    /// non-positive result).
    CalculationFailed,
}

// ─── SpotFundsPricingSource ───────────────────────────────────────────────────

/// Source the policy uses to derive the base price for a market order
/// before slippage is applied.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SpotFundsPricingSource {
    /// Use the stored `mark` price. The order would notionally be priced at
    /// `mark * (1 + slippage)` for buys and `mark * (1 - slippage)` for
    /// sells.
    ///
    /// Returns `SpotFundsPriceError::QuoteUnavailable` if the stored quote
    /// has no `mark` field.
    #[default]
    Mark,
    /// Use the side of the book that the order would cross: `ask` for buys
    /// and `bid` for sells. Slippage is added as a cushion on top
    /// (`ask * (1 + slippage)` / `bid * (1 - slippage)`).
    ///
    /// Returns `SpotFundsPriceError::QuoteUnavailable` if the relevant
    /// side of the book is missing from the stored quote - no implicit
    /// fallback to `mark`.
    BookTop,
}

// ─── SpotFundsOverride ────────────────────────────────────────────────────────

/// Override *value* applied at a slippage-cascade target.
///
/// Holds the slippage knob a [`SpotFundsOverrideTarget`] applies to the
/// instrument/account/account group it selects. Every field is optional: a `None`
/// means "fall back to the next tier of the cascade and ultimately the global
/// setting configured on the settings". The struct is named to flag its role as
/// the container for override knobs - future settings land here as additional
/// `Option<_>` fields, and call sites that initialise it via
/// `..Default::default()` keep compiling.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SpotFundsOverride {
    /// Slippage in basis points applied at the target. `None` defers to the
    /// next tier of the cascade (and ultimately the global `slippage_bps`
    /// configured on [`SpotFundsSettings::new`]).
    pub slippage_bps: Option<u16>,
}

// ─── SpotFundsOverrideTarget ──────────────────────────────────────────────────

/// Selects which accounts a [`SpotFundsOverride`] applies to within the
/// slippage resolution cascade.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpotFundsOverrideTarget {
    /// Instrument-level default: applies when no account- or account-group-scoped
    /// override matches the order's account.
    Instrument(InstrumentId),
    /// Applies to the instrument only for this exact account (highest priority).
    InstrumentAccount(InstrumentId, AccountId),
    /// Applies to the instrument only for accounts in this account group.
    InstrumentAccountGroup(InstrumentId, AccountGroupId),
}

// ─── SpotFundsSettings ────────────────────────────────────────────────────────

/// Runtime-updatable settings of [`SpotFundsPolicy`](super::SpotFundsPolicy).
///
/// Carries the slippage / pricing-source / override cascade. Slippage resolves
/// per order along three override scopes - per
/// `(instrument, account_id)`, per `(instrument, account_group_id)`, and per
/// `instrument` - falling back to the global slippage. The validated override
/// maps are precomputed here so hot-path reads through the policy's settings
/// cell allocate nothing and never recompute.
///
/// Built via [`SpotFundsSettings::new`] and handed to
/// [`SpotFundsPolicy::new`](super::SpotFundsPolicy::new); the slippage knobs are
/// then mutable at runtime through the setters.
#[derive(Clone, Debug)]
pub struct SpotFundsSettings {
    account_overrides: HashMap<(InstrumentId, AccountId), WithSlippage>,
    account_group_overrides: HashMap<(InstrumentId, AccountGroupId), WithSlippage>,
    instrument_overrides: HashMap<InstrumentId, WithSlippage>,
    global_pricer: WithSlippage,
    pricing_source: SpotFundsPricingSource,
}

impl SpotFundsSettings {
    /// Builds the cascade from the full set of configuration parameters.
    ///
    /// Pass `SpotFundsPricingSource::Mark` for the default source and `[]` (or
    /// any empty iterator) for no overrides. The instance starts with the
    /// default policy group; assign a tag via
    /// [`SpotFundsPolicy::with_policy_group_id`](super::SpotFundsPolicy::with_policy_group_id).
    ///
    /// Each `(target, override)` pair places a [`SpotFundsOverride`] into one
    /// of three slippage scopes selected by [`SpotFundsOverrideTarget`]: per
    /// `(instrument, account_id)`, per `(instrument, account_group_id)`, or
    /// per-instrument default. The slippage for an order resolves
    /// account -> account group -> instrument -> global. An override whose
    /// `slippage_bps` is `None` is ignored (the cascade falls through to the
    /// next tier).
    ///
    /// Returns [`SpotFundsConfigError::SlippageOutOfRange`] when
    /// `slippage_bps > 10_000` or when any override carries a `slippage_bps`
    /// above the same bound.
    pub fn new<Overrides>(
        slippage_bps: u16,
        pricing_source: SpotFundsPricingSource,
        overrides: Overrides,
    ) -> Result<Self, SpotFundsConfigError>
    where
        Overrides: IntoIterator<Item = (SpotFundsOverrideTarget, SpotFundsOverride)>,
    {
        check_slippage_bps(slippage_bps)?;
        let global_pricer = WithSlippage::new(slippage_bps);
        let mut account_overrides = HashMap::new();
        let mut account_group_overrides = HashMap::new();
        let mut instrument_overrides = HashMap::new();
        for (target, ovr) in overrides {
            let Some(bps) = ovr.slippage_bps else {
                continue;
            };
            check_slippage_bps(bps)?;
            let pricer = WithSlippage::new(bps);
            match target {
                SpotFundsOverrideTarget::Instrument(instrument_id) => {
                    instrument_overrides.insert(instrument_id, pricer);
                }
                SpotFundsOverrideTarget::InstrumentAccount(instrument_id, account_id) => {
                    account_overrides.insert((instrument_id, account_id), pricer);
                }
                SpotFundsOverrideTarget::InstrumentAccountGroup(
                    instrument_id,
                    account_group_id,
                ) => {
                    account_group_overrides.insert((instrument_id, account_group_id), pricer);
                }
            }
        }
        Ok(Self {
            account_overrides,
            account_group_overrides,
            instrument_overrides,
            global_pricer,
            pricing_source,
        })
    }

    /// Replaces the global slippage applied when no override matches.
    ///
    /// Returns [`SpotFundsConfigError::SlippageOutOfRange`] when
    /// `slippage_bps > 10_000`; the prior value is left unchanged on error.
    pub fn set_global_slippage_bps(
        &mut self,
        slippage_bps: u16,
    ) -> Result<(), SpotFundsConfigError> {
        check_slippage_bps(slippage_bps)?;
        self.global_pricer = WithSlippage::new(slippage_bps);
        Ok(())
    }

    /// Sets the source used to derive the base price before slippage.
    pub fn set_pricing_source(&mut self, pricing_source: SpotFundsPricingSource) {
        self.pricing_source = pricing_source;
    }

    /// Inserts or replaces a slippage override at the given cascade target.
    ///
    /// A `slippage_bps` of `None` clears any override previously set at the
    /// target, so the cascade falls through to the next tier. Returns
    /// [`SpotFundsConfigError::SlippageOutOfRange`] when the value exceeds
    /// 10 000 bps; the prior override is left unchanged on error.
    pub fn set_override(
        &mut self,
        target: SpotFundsOverrideTarget,
        ovr: SpotFundsOverride,
    ) -> Result<(), SpotFundsConfigError> {
        if let Some(bps) = ovr.slippage_bps {
            check_slippage_bps(bps)?;
        }
        let pricer = ovr.slippage_bps.map(WithSlippage::new);
        match target {
            SpotFundsOverrideTarget::Instrument(instrument_id) => {
                set_or_clear(&mut self.instrument_overrides, instrument_id, pricer);
            }
            SpotFundsOverrideTarget::InstrumentAccount(instrument_id, account_id) => {
                set_or_clear(
                    &mut self.account_overrides,
                    (instrument_id, account_id),
                    pricer,
                );
            }
            SpotFundsOverrideTarget::InstrumentAccountGroup(instrument_id, account_group_id) => {
                set_or_clear(
                    &mut self.account_group_overrides,
                    (instrument_id, account_group_id),
                    pricer,
                );
            }
        }
        Ok(())
    }

    /// Selects the slippage pricer for an order via the resolution cascade.
    fn pricer_for(
        &self,
        instrument_id: InstrumentId,
        account_id: AccountId,
        account_info: &impl AccountInfo,
    ) -> &WithSlippage {
        if let Some(p) = self.account_overrides.get(&(instrument_id, account_id)) {
            return p;
        }
        if let Some(account_group_id) = account_info.group() {
            if let Some(p) = self
                .account_group_overrides
                .get(&(instrument_id, account_group_id))
            {
                return p;
            }
        }
        if let Some(p) = self.instrument_overrides.get(&instrument_id) {
            return p;
        }
        &self.global_pricer
    }

    /// Raw quote field used as the base for buy-side pricing before slippage
    /// is applied; `None` when the relevant field is missing from the quote.
    fn pricing_base_for_buy(&self, quote: &Quote) -> Option<Price> {
        match self.pricing_source {
            SpotFundsPricingSource::Mark => quote.mark,
            SpotFundsPricingSource::BookTop => quote.ask,
        }
    }

    /// Raw quote field used as the base for sell-side pricing before slippage
    /// is applied; `None` when the relevant field is missing from the quote.
    fn pricing_base_for_sell(&self, quote: &Quote) -> Option<Price> {
        match self.pricing_source {
            SpotFundsPricingSource::Mark => quote.mark,
            SpotFundsPricingSource::BookTop => quote.bid,
        }
    }

    /// Effective buy price for `quote` under the resolved slippage tier.
    pub(super) fn effective_buy_price(
        &self,
        quote: &Quote,
        instrument_id: InstrumentId,
        account_id: AccountId,
        account_info: &impl AccountInfo,
    ) -> Result<Price, SpotFundsPriceError> {
        let base = self
            .pricing_base_for_buy(quote)
            .ok_or(SpotFundsPriceError::QuoteUnavailable)?;
        self.pricer_for(instrument_id, account_id, account_info)
            .effective_buy_price(base)
            .map_err(|_| SpotFundsPriceError::CalculationFailed)
    }

    /// Effective sell price for `quote` under the resolved slippage tier.
    pub(super) fn effective_sell_price(
        &self,
        quote: &Quote,
        instrument_id: InstrumentId,
        account_id: AccountId,
        account_info: &impl AccountInfo,
    ) -> Result<Price, SpotFundsPriceError> {
        let base = self
            .pricing_base_for_sell(quote)
            .ok_or(SpotFundsPriceError::QuoteUnavailable)?;
        self.pricer_for(instrument_id, account_id, account_info)
            .effective_sell_price(base)
            .map_err(|_| SpotFundsPriceError::CalculationFailed)
    }
}

/// Inserts `value` at `key`, or removes the entry when `value` is `None`.
fn set_or_clear<K, V>(map: &mut HashMap<K, V>, key: K, value: Option<V>)
where
    K: std::hash::Hash + Eq,
{
    match value {
        Some(v) => {
            map.insert(key, v);
        }
        None => {
            map.remove(&key);
        }
    }
}

// ─── SpotFundsMarketData ──────────────────────────────────────────────────────

/// Market-data service handle for [`SpotFundsPolicy`](super::SpotFundsPolicy).
///
/// Wraps the shared [`MarketDataService`] handle the policy consults to price
/// market orders. The handle is fixed for the policy's lifetime; the slippage
/// and pricing cascade applied on top of the quotes lives in the
/// runtime-updatable [`SpotFundsSettings`].
///
/// Pass `None` to [`SpotFundsPolicy::new`](super::SpotFundsPolicy::new) to
/// disable market orders entirely (rejected with
/// [`crate::pretrade::RejectCode::UnsupportedOrderType`]).
pub struct SpotFundsMarketData<Sync: MarketDataSync> {
    pub(super) market_data: Sync::Shared<MarketDataService<Sync>>,
}

impl<Sync: MarketDataSync> SpotFundsMarketData<Sync> {
    /// Wraps the shared market-data service handle.
    pub fn new(market_data: Sync::Shared<MarketDataService<Sync>>) -> Self {
        Self { market_data }
    }

    /// Latest usable quote for `(instrument_id, account_id)` under the widest
    /// resolution; `None` when no usable quote is available.
    pub(super) fn quote(
        &self,
        instrument_id: InstrumentId,
        account_id: AccountId,
        account_info: &impl AccountInfo,
    ) -> Option<Quote> {
        self.market_data
            .get(
                instrument_id,
                account_id,
                account_info,
                QuoteResolution::AccountThenGroupThenDefault,
            )
            .ok()
    }

    pub(super) fn resolve(&self, instrument: &Instrument) -> Option<InstrumentId> {
        self.market_data.resolve(instrument)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::marketdata::{MarketDataBuilder, Quote, QuoteTtl};
    use crate::param::{Asset, Price};
    use crate::FullSync;

    fn px(s: &str) -> Price {
        Price::from_str(s).expect("valid price")
    }

    fn asset(s: &str) -> Asset {
        Asset::new(s).expect("valid asset")
    }

    fn account(n: u64) -> AccountId {
        AccountId::from_u64(n)
    }

    fn group(n: u32) -> AccountGroupId {
        AccountGroupId::from_u32(n).expect("valid account group id")
    }

    /// Registers `AAPL/USD` with `mark = 100` in the default bucket and returns
    /// the service handle plus the instrument id. The default bucket is
    /// reachable by any account under `AccountThenGroupThenDefault`, so every
    /// effective-price call below shares the same base price and any change in
    /// the result is attributable solely to the slippage tier selected.
    fn service_with_mark_100() -> (Arc<MarketDataService<FullSync>>, InstrumentId) {
        let svc = MarketDataBuilder::<FullSync>::new(QuoteTtl::Infinite).build();
        let id = svc
            .register(Instrument::new(asset("AAPL"), asset("USD")))
            .expect("register must succeed");
        svc.push(id, Quote::new().with_mark(px("100")))
            .expect("push must succeed");
        (svc, id)
    }

    /// Resolves the effective buy price for `settings` against `svc`,
    /// mirroring the policy's quote-then-price hot path.
    fn buy_price_of(
        svc: &Arc<MarketDataService<FullSync>>,
        settings: &SpotFundsSettings,
        id: InstrumentId,
        account_id: AccountId,
        account_info: &impl AccountInfo,
    ) -> Result<Price, SpotFundsPriceError> {
        let md = SpotFundsMarketData::<FullSync>::new(Arc::clone(svc));
        let quote = md
            .quote(id, account_id, account_info)
            .ok_or(SpotFundsPriceError::QuoteUnavailable)?;
        settings.effective_buy_price(&quote, id, account_id, account_info)
    }

    /// Resolves the effective sell price for `settings` against `svc`,
    /// mirroring the policy's quote-then-price hot path.
    fn sell_price_of(
        svc: &Arc<MarketDataService<FullSync>>,
        settings: &SpotFundsSettings,
        id: InstrumentId,
        account_id: AccountId,
        account_info: &impl AccountInfo,
    ) -> Result<Price, SpotFundsPriceError> {
        let md = SpotFundsMarketData::<FullSync>::new(Arc::clone(svc));
        let quote = md
            .quote(id, account_id, account_info)
            .ok_or(SpotFundsPriceError::QuoteUnavailable)?;
        settings.effective_sell_price(&quote, id, account_id, account_info)
    }

    fn buy_price<Overrides>(
        slippage_bps: u16,
        overrides: Overrides,
        account_id: AccountId,
        account_info: &impl AccountInfo,
    ) -> Result<Price, SpotFundsPriceError>
    where
        Overrides: IntoIterator<Item = (SpotFundsOverrideTarget, SpotFundsOverride)>,
    {
        let (svc, id) = service_with_mark_100();
        let settings =
            SpotFundsSettings::new(slippage_bps, SpotFundsPricingSource::Mark, overrides)
                .expect("settings must build");
        buy_price_of(&svc, &settings, id, account_id, account_info)
    }

    #[test]
    fn account_override_wins_over_group_instrument_and_global() {
        let (svc, id) = service_with_mark_100();
        let acc = account(7);
        let grp = group(3);
        // global 0, instrument 1000, group 2000, account 3000 bps.
        let overrides = [
            (
                SpotFundsOverrideTarget::Instrument(id),
                SpotFundsOverride {
                    slippage_bps: Some(1000),
                },
            ),
            (
                SpotFundsOverrideTarget::InstrumentAccountGroup(id, grp),
                SpotFundsOverride {
                    slippage_bps: Some(2000),
                },
            ),
            (
                SpotFundsOverrideTarget::InstrumentAccount(id, acc),
                SpotFundsOverride {
                    slippage_bps: Some(3000),
                },
            ),
        ];
        let settings = SpotFundsSettings::new(0, SpotFundsPricingSource::Mark, overrides)
            .expect("settings must build");
        // 100 * (1 + 0.30) = 130 - account tier wins even though the account
        // is also in the matching group.
        assert_eq!(
            buy_price_of(&svc, &settings, id, acc, &Some(grp)),
            Ok(px("130"))
        );
    }

    #[test]
    fn group_override_used_when_no_account_override_matches() {
        let acc = account(7);
        let grp = group(3);
        let (svc, id) = service_with_mark_100();
        let overrides = [
            (
                SpotFundsOverrideTarget::Instrument(id),
                SpotFundsOverride {
                    slippage_bps: Some(1000),
                },
            ),
            (
                SpotFundsOverrideTarget::InstrumentAccountGroup(id, grp),
                SpotFundsOverride {
                    slippage_bps: Some(2000),
                },
            ),
        ];
        let settings = SpotFundsSettings::new(0, SpotFundsPricingSource::Mark, overrides)
            .expect("settings must build");
        // No account override, account is in group 3 -> 100 * 1.20 = 120.
        assert_eq!(
            buy_price_of(&svc, &settings, id, acc, &Some(grp)),
            Ok(px("120"))
        );
    }

    #[test]
    fn instrument_default_used_when_neither_account_nor_group_matches() {
        let acc = account(7);
        let (svc, id) = service_with_mark_100();
        let settings = SpotFundsSettings::new(
            0,
            SpotFundsPricingSource::Mark,
            [(
                SpotFundsOverrideTarget::Instrument(id),
                SpotFundsOverride {
                    slippage_bps: Some(1000),
                },
            )],
        )
        .expect("settings must build");
        // Account info yields no account group, so the account-group tier is
        // skipped entirely and the instrument default (1000 bps) applies -> 110.
        assert_eq!(buy_price_of(&svc, &settings, id, acc, &None), Ok(px("110")));
        // A present but non-matching group still falls through to instrument.
        assert_eq!(
            buy_price_of(&svc, &settings, id, acc, &Some(group(9))),
            Ok(px("110"))
        );
    }

    #[test]
    fn global_used_when_nothing_matches() {
        let acc = account(7);
        // Global 1000 bps, no overrides at all -> 100 * 1.10 = 110.
        assert_eq!(
            buy_price(1000, std::iter::empty(), acc, &None),
            Ok(px("110"))
        );
    }

    #[test]
    fn none_slippage_override_entry_is_treated_as_absent() {
        let acc = account(7);
        let grp = group(3);
        let (svc, id) = service_with_mark_100();
        // Account and group entries both carry None -> ignored, so the cascade
        // falls through to the instrument default (1000 bps = 110).
        let overrides = [
            (
                SpotFundsOverrideTarget::InstrumentAccount(id, acc),
                SpotFundsOverride { slippage_bps: None },
            ),
            (
                SpotFundsOverrideTarget::InstrumentAccountGroup(id, grp),
                SpotFundsOverride { slippage_bps: None },
            ),
            (
                SpotFundsOverrideTarget::Instrument(id),
                SpotFundsOverride {
                    slippage_bps: Some(1000),
                },
            ),
        ];
        let settings = SpotFundsSettings::new(0, SpotFundsPricingSource::Mark, overrides)
            .expect("settings must build");
        assert_eq!(
            buy_price_of(&svc, &settings, id, acc, &Some(grp)),
            Ok(px("110"))
        );
    }

    #[test]
    fn out_of_range_account_override_returns_slippage_out_of_range() {
        let (_svc, id) = service_with_mark_100();
        let result = SpotFundsSettings::new(
            0,
            SpotFundsPricingSource::Mark,
            [(
                SpotFundsOverrideTarget::InstrumentAccount(id, account(7)),
                SpotFundsOverride {
                    slippage_bps: Some(10_001),
                },
            )],
        );
        assert_eq!(
            result.err(),
            Some(SpotFundsConfigError::SlippageOutOfRange { bps: 10_001 })
        );
    }

    #[test]
    fn out_of_range_group_override_returns_slippage_out_of_range() {
        let (_svc, id) = service_with_mark_100();
        let result = SpotFundsSettings::new(
            0,
            SpotFundsPricingSource::Mark,
            [(
                SpotFundsOverrideTarget::InstrumentAccountGroup(id, group(3)),
                SpotFundsOverride {
                    slippage_bps: Some(10_001),
                },
            )],
        );
        assert_eq!(
            result.err(),
            Some(SpotFundsConfigError::SlippageOutOfRange { bps: 10_001 })
        );
    }

    // ── Sell-side cascade tests ───────────────────────────────────────────────
    //
    // Formula: mark * (1 - factor), factor = bps / 10_000, mark = 100.
    //   3000 bps -> 100 * 0.70 = 70
    //   2000 bps -> 100 * 0.80 = 80
    //   1000 bps -> 100 * 0.90 = 90
    //      0 bps -> 100 * 1.00 = 100

    fn sell_price<Overrides>(
        slippage_bps: u16,
        overrides: Overrides,
        account_id: AccountId,
        account_info: &impl AccountInfo,
    ) -> Result<Price, SpotFundsPriceError>
    where
        Overrides: IntoIterator<Item = (SpotFundsOverrideTarget, SpotFundsOverride)>,
    {
        let (svc, id) = service_with_mark_100();
        let settings =
            SpotFundsSettings::new(slippage_bps, SpotFundsPricingSource::Mark, overrides)
                .expect("settings must build");
        sell_price_of(&svc, &settings, id, account_id, account_info)
    }

    #[test]
    fn sell_account_override_wins_over_group_instrument_and_global() {
        let (svc, id) = service_with_mark_100();
        let acc = account(7);
        let grp = group(3);
        // global 0, instrument 1000, group 2000, account 3000 bps.
        let overrides = [
            (
                SpotFundsOverrideTarget::Instrument(id),
                SpotFundsOverride {
                    slippage_bps: Some(1000),
                },
            ),
            (
                SpotFundsOverrideTarget::InstrumentAccountGroup(id, grp),
                SpotFundsOverride {
                    slippage_bps: Some(2000),
                },
            ),
            (
                SpotFundsOverrideTarget::InstrumentAccount(id, acc),
                SpotFundsOverride {
                    slippage_bps: Some(3000),
                },
            ),
        ];
        let settings = SpotFundsSettings::new(0, SpotFundsPricingSource::Mark, overrides)
            .expect("settings must build");
        // 100 * (1 - 0.30) = 70 - account tier wins even though the
        // account is also in the matching group.
        assert_eq!(
            sell_price_of(&svc, &settings, id, acc, &Some(grp)),
            Ok(px("70"))
        );
    }

    #[test]
    fn sell_group_override_used_when_no_account_override_matches() {
        let acc = account(7);
        let grp = group(3);
        let (svc, id) = service_with_mark_100();
        let overrides = [
            (
                SpotFundsOverrideTarget::Instrument(id),
                SpotFundsOverride {
                    slippage_bps: Some(1000),
                },
            ),
            (
                SpotFundsOverrideTarget::InstrumentAccountGroup(id, grp),
                SpotFundsOverride {
                    slippage_bps: Some(2000),
                },
            ),
        ];
        let settings = SpotFundsSettings::new(0, SpotFundsPricingSource::Mark, overrides)
            .expect("settings must build");
        // No account override; account is in group 3 -> 100 * 0.80 = 80.
        assert_eq!(
            sell_price_of(&svc, &settings, id, acc, &Some(grp)),
            Ok(px("80"))
        );
    }

    #[test]
    fn sell_instrument_default_used_when_neither_account_nor_group_matches() {
        let acc = account(7);
        let (svc, id) = service_with_mark_100();
        let settings = SpotFundsSettings::new(
            0,
            SpotFundsPricingSource::Mark,
            [(
                SpotFundsOverrideTarget::Instrument(id),
                SpotFundsOverride {
                    slippage_bps: Some(1000),
                },
            )],
        )
        .expect("settings must build");
        // No account group -> instrument default 1000 bps -> 100 * 0.90 = 90.
        assert_eq!(sell_price_of(&svc, &settings, id, acc, &None), Ok(px("90")));
        // A present but non-matching group still falls through to
        // the instrument default.
        assert_eq!(
            sell_price_of(&svc, &settings, id, acc, &Some(group(9))),
            Ok(px("90"))
        );
    }

    #[test]
    fn sell_global_used_when_nothing_matches() {
        let acc = account(7);
        // Global 1000 bps, no overrides -> 100 * (1 - 0.10) = 90.
        assert_eq!(
            sell_price(1000, std::iter::empty(), acc, &None),
            Ok(px("90"))
        );
    }
}