Skip to main content

nautilus_execution/models/
fee.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::{fmt::Debug, rc::Rc};
17
18use nautilus_model::{
19    enums::LiquiditySide,
20    fees::{MakerTakerFeeRates, MakerTakerFeeSchedule, calculate_maker_taker_commission},
21    identifiers::{GENERIC_SPREAD_ID_SEPARATOR, InstrumentId, parse_generic_spread_id_legs},
22    instruments::{Instrument, InstrumentAny},
23    orders::{Order, OrderAny},
24    types::{Currency, Money, Price, Quantity},
25};
26use rust_decimal::Decimal;
27use rust_decimal_macros::dec;
28
29#[cfg(feature = "python")]
30use crate::python::fee::{PyFeeModel, PythonFeeModel};
31
32pub trait FeeModel {
33    /// Calculates commission for a fill.
34    ///
35    /// # Errors
36    ///
37    /// Returns an error if commission calculation fails.
38    fn get_commission(
39        &self,
40        order: &OrderAny,
41        fill_quantity: Quantity,
42        fill_px: Price,
43        instrument: &InstrumentAny,
44    ) -> anyhow::Result<Money>;
45
46    /// Calculates commission for a fill with additional pricing context.
47    ///
48    /// # Errors
49    ///
50    /// Returns an error if commission calculation fails.
51    fn get_commission_with_context(
52        &self,
53        order: &OrderAny,
54        fill_quantity: Quantity,
55        fill_px: Price,
56        instrument: &InstrumentAny,
57        _underlying_px: Option<Price>,
58    ) -> anyhow::Result<Money> {
59        self.get_commission(order, fill_quantity, fill_px, instrument)
60    }
61}
62
63/// Shared runtime handle for a fee model.
64#[derive(Clone)]
65pub struct FeeModelHandle(Rc<dyn FeeModel>);
66
67impl FeeModelHandle {
68    /// Creates a new [`FeeModelHandle`] from a fee model.
69    #[must_use]
70    pub fn new<T>(model: T) -> Self
71    where
72        T: FeeModel + 'static,
73    {
74        Self(Rc::new(model))
75    }
76
77    /// Creates a new [`FeeModelHandle`] from an existing reference-counted model.
78    #[must_use]
79    pub fn from_rc(model: Rc<dyn FeeModel>) -> Self {
80        Self(model)
81    }
82}
83
84impl Debug for FeeModelHandle {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        f.debug_tuple(stringify!(FeeModelHandle))
87            .field(&"<dyn FeeModel>")
88            .finish()
89    }
90}
91
92impl FeeModel for FeeModelHandle {
93    fn get_commission(
94        &self,
95        order: &OrderAny,
96        fill_quantity: Quantity,
97        fill_px: Price,
98        instrument: &InstrumentAny,
99    ) -> anyhow::Result<Money> {
100        self.0
101            .get_commission(order, fill_quantity, fill_px, instrument)
102    }
103
104    fn get_commission_with_context(
105        &self,
106        order: &OrderAny,
107        fill_quantity: Quantity,
108        fill_px: Price,
109        instrument: &InstrumentAny,
110        underlying_px: Option<Price>,
111    ) -> anyhow::Result<Money> {
112        self.0
113            .get_commission_with_context(order, fill_quantity, fill_px, instrument, underlying_px)
114    }
115}
116
117impl From<FeeModelAny> for FeeModelHandle {
118    fn from(model: FeeModelAny) -> Self {
119        Self::new(model)
120    }
121}
122
123#[derive(Clone, Debug)]
124pub enum FeeModelAny {
125    Fixed(FixedFeeModel),
126    MakerTaker(MakerTakerFeeModel),
127    PerContract(PerContractFeeModel),
128    ProbabilityPrice(ProbabilityPriceFeeModel),
129    CappedOption(CappedOptionFeeModel),
130    TieredNotionalOption(TieredNotionalOptionFeeModel),
131    #[cfg(feature = "python")]
132    Python(PythonFeeModel),
133}
134
135impl FeeModel for FeeModelAny {
136    #[rustfmt::skip]
137    fn get_commission(
138        &self,
139        order: &OrderAny,
140        fill_quantity: Quantity,
141        fill_px: Price,
142        instrument: &InstrumentAny,
143    ) -> anyhow::Result<Money> {
144        match self {
145            Self::Fixed(model) => model.get_commission(order, fill_quantity, fill_px, instrument),
146            Self::MakerTaker(model) => model.get_commission(order, fill_quantity, fill_px, instrument),
147            Self::PerContract(model) => model.get_commission(order, fill_quantity, fill_px, instrument),
148            Self::ProbabilityPrice(model) => model.get_commission(order, fill_quantity, fill_px, instrument),
149            Self::CappedOption(model) => model.get_commission(order, fill_quantity, fill_px, instrument),
150            Self::TieredNotionalOption(model) => model.get_commission(order, fill_quantity, fill_px, instrument),
151            #[cfg(feature = "python")]
152            Self::Python(model) => model.get_commission(order, fill_quantity, fill_px, instrument),
153        }
154    }
155
156    #[rustfmt::skip]
157    fn get_commission_with_context(
158        &self,
159        order: &OrderAny,
160        fill_quantity: Quantity,
161        fill_px: Price,
162        instrument: &InstrumentAny,
163        underlying_px: Option<Price>,
164    ) -> anyhow::Result<Money> {
165        match self {
166            Self::Fixed(model) => model.get_commission_with_context(order, fill_quantity, fill_px, instrument, underlying_px),
167            Self::MakerTaker(model) => model.get_commission_with_context(order, fill_quantity, fill_px, instrument, underlying_px),
168            Self::PerContract(model) => model.get_commission_with_context(order, fill_quantity, fill_px, instrument, underlying_px),
169            Self::ProbabilityPrice(model) => model.get_commission_with_context(order, fill_quantity, fill_px, instrument, underlying_px),
170            Self::CappedOption(model) => model.get_commission_with_context(order, fill_quantity, fill_px, instrument, underlying_px),
171            Self::TieredNotionalOption(model) => model.get_commission_with_context(order, fill_quantity, fill_px, instrument, underlying_px),
172            #[cfg(feature = "python")]
173            Self::Python(model) => model.get_commission_with_context(order, fill_quantity, fill_px, instrument, underlying_px),
174        }
175    }
176}
177
178#[derive(Debug, Clone)]
179#[cfg_attr(
180    feature = "python",
181    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
182)]
183#[cfg_attr(
184    feature = "python",
185    pyo3::pyclass(
186        module = "nautilus_trader.execution",
187        extends = PyFeeModel,
188    )
189)]
190pub struct FixedFeeModel {
191    commission: Money,
192    zero_commission: Money,
193    charge_commission_once: bool,
194}
195
196impl FixedFeeModel {
197    /// Creates a new [`FixedFeeModel`] instance.
198    ///
199    /// # Errors
200    ///
201    /// Returns an error if `commission` is negative.
202    pub fn new(commission: Money, charge_commission_once: Option<bool>) -> anyhow::Result<Self> {
203        if commission.is_negative() {
204            anyhow::bail!("Commission must be greater than or equal to zero")
205        }
206        let zero_commission = Money::zero(commission.currency);
207        Ok(Self {
208            commission,
209            zero_commission,
210            charge_commission_once: charge_commission_once.unwrap_or(true),
211        })
212    }
213}
214
215impl FeeModel for FixedFeeModel {
216    fn get_commission(
217        &self,
218        order: &OrderAny,
219        _fill_quantity: Quantity,
220        _fill_px: Price,
221        _instrument: &InstrumentAny,
222    ) -> anyhow::Result<Money> {
223        if !self.charge_commission_once || order.filled_qty().is_zero() {
224            Ok(self.commission)
225        } else {
226            Ok(self.zero_commission)
227        }
228    }
229}
230
231#[derive(Debug, Clone)]
232#[cfg_attr(
233    feature = "python",
234    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
235)]
236#[cfg_attr(
237    feature = "python",
238    pyo3::pyclass(
239        module = "nautilus_trader.execution",
240        extends = PyFeeModel,
241    )
242)]
243pub struct PerContractFeeModel {
244    commission: Money,
245}
246
247impl PerContractFeeModel {
248    /// Creates a new [`PerContractFeeModel`] instance.
249    ///
250    /// # Errors
251    ///
252    /// Returns an error if `commission` is negative.
253    pub fn new(commission: Money) -> anyhow::Result<Self> {
254        if commission.is_negative() {
255            anyhow::bail!("Commission must be greater than or equal to zero")
256        }
257        Ok(Self { commission })
258    }
259}
260
261fn mul_checked(lhs: Decimal, rhs: Decimal) -> anyhow::Result<Decimal> {
262    lhs.checked_mul(rhs)
263        .ok_or_else(|| anyhow::anyhow!("commission calculation overflow"))
264}
265
266impl FeeModel for PerContractFeeModel {
267    fn get_commission(
268        &self,
269        _order: &OrderAny,
270        fill_quantity: Quantity,
271        _fill_px: Price,
272        instrument: &InstrumentAny,
273    ) -> anyhow::Result<Money> {
274        let contracts = spread_contract_count(instrument)?;
275        let total = mul_checked(self.commission.as_decimal(), fill_quantity.as_decimal())
276            .and_then(|v| mul_checked(v, contracts))?;
277        Money::from_decimal(total, self.commission.currency).map_err(Into::into)
278    }
279}
280
281fn spread_contract_count(instrument: &InstrumentAny) -> anyhow::Result<Decimal> {
282    let instrument_id = instrument.id();
283    let symbol = instrument_id.symbol.as_str();
284    if !instrument.is_spread() || !symbol.contains(GENERIC_SPREAD_ID_SEPARATOR) {
285        return Ok(Decimal::ONE);
286    }
287
288    let mut total = 0_i64;
289
290    for (_, ratio) in parse_generic_spread_id_legs(&instrument_id)? {
291        total = total.checked_add(ratio.abs()).ok_or_else(|| {
292            anyhow::anyhow!("Generic spread contract count overflowed for {symbol}")
293        })?;
294    }
295
296    Ok(total.into())
297}
298
299#[derive(Debug, Clone)]
300#[cfg_attr(
301    feature = "python",
302    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
303)]
304#[cfg_attr(
305    feature = "python",
306    pyo3::pyclass(
307        module = "nautilus_trader.execution",
308        extends = PyFeeModel,
309    )
310)]
311pub struct MakerTakerFeeModel {
312    schedule: MakerTakerFeeSchedule,
313}
314
315impl MakerTakerFeeModel {
316    /// Creates a new [`MakerTakerFeeModel`] with explicit default rates.
317    ///
318    /// Negative maker rates represent rebates where the venue supports them.
319    /// Use [`Self::set_override`] for exact per-instrument rates.
320    #[must_use]
321    pub fn new(maker_rate: Decimal, taker_rate: Decimal) -> Self {
322        Self {
323            schedule: MakerTakerFeeSchedule::new(maker_rate, taker_rate),
324        }
325    }
326
327    /// Creates a new explicit zero-fee [`MakerTakerFeeModel`].
328    #[must_use]
329    pub fn zero() -> Self {
330        Self {
331            schedule: MakerTakerFeeSchedule::zero(),
332        }
333    }
334
335    /// Adds or replaces an exact instrument override.
336    pub fn set_override(&mut self, instrument_id: InstrumentId, rates: MakerTakerFeeRates) {
337        self.schedule.set_override(instrument_id, rates);
338    }
339
340    /// Returns the owned fee schedule.
341    #[must_use]
342    pub fn schedule(&self) -> &MakerTakerFeeSchedule {
343        &self.schedule
344    }
345}
346
347impl FeeModel for MakerTakerFeeModel {
348    fn get_commission(
349        &self,
350        order: &OrderAny,
351        fill_quantity: Quantity,
352        fill_px: Price,
353        instrument: &InstrumentAny,
354    ) -> anyhow::Result<Money> {
355        let liquidity_side = order
356            .liquidity_side()
357            .ok_or_else(|| anyhow::anyhow!("Liquidity side not set"))?;
358        if liquidity_side == LiquiditySide::NoLiquiditySide {
359            anyhow::bail!("Liquidity side not set");
360        }
361
362        let rate = self.schedule.rate_for(instrument.id(), liquidity_side)?;
363        calculate_maker_taker_commission(instrument, fill_quantity, fill_px, rate, Some(false))
364    }
365}
366
367/// Fee model for probability-priced outcome shares.
368///
369/// Applies `qty * fee_rate * p * (1 - p)` using the account-owned maker or
370/// taker fee rate. This matches venues that represent outcome shares as
371/// [`InstrumentAny::BinaryOption`] instruments quoted on a `[0, 1]`
372/// probability scale.
373///
374/// This model covers quote-currency match-time exchange fees only.
375/// Venue-specific rebate programs or non-quote fee assets remain outside the
376/// core execution layer.
377#[derive(Debug, Clone)]
378#[cfg_attr(
379    feature = "python",
380    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
381)]
382#[cfg_attr(
383    feature = "python",
384    pyo3::pyclass(
385        module = "nautilus_trader.execution",
386        extends = PyFeeModel,
387    )
388)]
389pub struct ProbabilityPriceFeeModel {
390    schedule: MakerTakerFeeSchedule,
391}
392
393impl ProbabilityPriceFeeModel {
394    /// Creates a new [`ProbabilityPriceFeeModel`] with explicit default rates.
395    #[must_use]
396    pub fn new(maker_rate: Decimal, taker_rate: Decimal) -> Self {
397        Self {
398            schedule: MakerTakerFeeSchedule::new(maker_rate, taker_rate),
399        }
400    }
401
402    /// Adds or replaces an exact instrument override.
403    pub fn set_override(&mut self, instrument_id: InstrumentId, rates: MakerTakerFeeRates) {
404        self.schedule.set_override(instrument_id, rates);
405    }
406
407    /// Returns the owned fee schedule.
408    #[must_use]
409    pub fn schedule(&self) -> &MakerTakerFeeSchedule {
410        &self.schedule
411    }
412}
413
414impl FeeModel for ProbabilityPriceFeeModel {
415    fn get_commission(
416        &self,
417        order: &OrderAny,
418        fill_quantity: Quantity,
419        fill_px: Price,
420        instrument: &InstrumentAny,
421    ) -> anyhow::Result<Money> {
422        if !matches!(instrument, InstrumentAny::BinaryOption(_)) {
423            anyhow::bail!("ProbabilityPriceFeeModel requires a binary option instrument");
424        }
425
426        let fill_price = fill_px.as_decimal();
427        if !(Decimal::ZERO..=Decimal::ONE).contains(&fill_price) {
428            anyhow::bail!("ProbabilityPriceFeeModel requires a fill price in [0, 1]");
429        }
430
431        let liquidity_side = order
432            .liquidity_side()
433            .ok_or_else(|| anyhow::anyhow!("Liquidity side not set"))?;
434        if liquidity_side == LiquiditySide::NoLiquiditySide {
435            anyhow::bail!("Liquidity side not set");
436        }
437
438        let fee_rate = self.schedule.rate_for(instrument.id(), liquidity_side)?;
439
440        let one_minus_p = Decimal::ONE - fill_price;
441        let commission = mul_checked(fill_quantity.as_decimal(), fee_rate)
442            .and_then(|v| mul_checked(v, fill_price))
443            .and_then(|v| mul_checked(v, one_minus_p))
444            .map(|v| v.round_dp(5))?;
445
446        Money::from_decimal(commission, instrument.quote_currency()).map_err(Into::into)
447    }
448}
449
450#[derive(Debug, Clone)]
451#[cfg_attr(
452    feature = "python",
453    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
454)]
455#[cfg_attr(
456    feature = "python",
457    pyo3::pyclass(
458        module = "nautilus_trader.execution",
459        extends = PyFeeModel,
460    )
461)]
462pub struct CappedOptionFeeModel {
463    schedule: MakerTakerFeeSchedule,
464    cap: Decimal,
465}
466
467impl CappedOptionFeeModel {
468    /// Creates a new [`CappedOptionFeeModel`] instance with explicit rates.
469    ///
470    /// # Errors
471    ///
472    /// Returns an error if any supplied rate is negative.
473    pub fn new(
474        maker_rate: Decimal,
475        taker_rate: Decimal,
476        cap_rate: Option<Decimal>,
477    ) -> anyhow::Result<Self> {
478        check_fee_rate(maker_rate, "maker_rate")?;
479        check_fee_rate(taker_rate, "taker_rate")?;
480
481        let cap_rate = cap_rate.unwrap_or(dec!(0.125));
482        check_fee_rate(cap_rate, "cap_rate")?;
483
484        Ok(Self {
485            schedule: MakerTakerFeeSchedule::new(maker_rate, taker_rate),
486            cap: cap_rate,
487        })
488    }
489
490    /// Adds or replaces an exact instrument override.
491    ///
492    /// # Errors
493    ///
494    /// Returns an error if any override rate is negative.
495    pub fn set_override(
496        &mut self,
497        instrument_id: InstrumentId,
498        rates: MakerTakerFeeRates,
499    ) -> anyhow::Result<()> {
500        check_fee_rate(rates.maker, "maker_rate")?;
501        check_fee_rate(rates.taker, "taker_rate")?;
502        self.schedule.set_override(instrument_id, rates);
503        Ok(())
504    }
505
506    /// Returns the owned fee schedule.
507    #[must_use]
508    pub fn schedule(&self) -> &MakerTakerFeeSchedule {
509        &self.schedule
510    }
511}
512
513impl FeeModel for CappedOptionFeeModel {
514    fn get_commission(
515        &self,
516        order: &OrderAny,
517        fill_quantity: Quantity,
518        fill_px: Price,
519        instrument: &InstrumentAny,
520    ) -> anyhow::Result<Money> {
521        self.get_commission_with_context(order, fill_quantity, fill_px, instrument, None)
522    }
523
524    fn get_commission_with_context(
525        &self,
526        order: &OrderAny,
527        fill_quantity: Quantity,
528        fill_px: Price,
529        instrument: &InstrumentAny,
530        underlying_px: Option<Price>,
531    ) -> anyhow::Result<Money> {
532        check_option_instrument(instrument, "CappedOptionFeeModel")?;
533        let liquidity_side = order
534            .liquidity_side()
535            .ok_or_else(|| anyhow::anyhow!("Liquidity side not set"))?;
536        if liquidity_side == LiquiditySide::NoLiquiditySide {
537            anyhow::bail!("Liquidity side not set");
538        }
539
540        let rate = self.schedule.rate_for(instrument.id(), liquidity_side)?;
541        check_fee_rate(rate, "fee_rate")?;
542        let multiplier = instrument.multiplier().as_decimal();
543        let rate_fee = if instrument.is_inverse() {
544            rate
545        } else {
546            let underlying_px =
547                underlying_px.ok_or_else(|| anyhow::anyhow!("Underlying price is required"))?;
548            mul_checked(rate, underlying_px.as_decimal())?
549        };
550        let cap_fee = mul_checked(self.cap, fill_px.as_decimal())?;
551        let fee_per_contract = mul_checked(rate_fee.min(cap_fee), multiplier)?;
552        let total = mul_checked(fee_per_contract, fill_quantity.as_decimal())?;
553        Money::from_decimal(total, commission_currency(instrument)).map_err(Into::into)
554    }
555}
556
557#[derive(Debug, Clone)]
558#[cfg_attr(
559    feature = "python",
560    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.execution")
561)]
562#[cfg_attr(
563    feature = "python",
564    pyo3::pyclass(
565        module = "nautilus_trader.execution",
566        extends = PyFeeModel,
567    )
568)]
569pub struct TieredNotionalOptionFeeModel {
570    schedule: MakerTakerFeeSchedule,
571}
572
573impl TieredNotionalOptionFeeModel {
574    /// Creates a new [`TieredNotionalOptionFeeModel`] instance with explicit rates.
575    ///
576    /// # Errors
577    ///
578    /// Returns an error if any supplied rate is negative.
579    pub fn new(maker_rate: Decimal, taker_rate: Decimal) -> anyhow::Result<Self> {
580        check_fee_rate(maker_rate, "maker_rate")?;
581        check_fee_rate(taker_rate, "taker_rate")?;
582
583        Ok(Self {
584            schedule: MakerTakerFeeSchedule::new(maker_rate, taker_rate),
585        })
586    }
587
588    /// Adds or replaces an exact instrument override.
589    ///
590    /// # Errors
591    ///
592    /// Returns an error if any override rate is negative.
593    pub fn set_override(
594        &mut self,
595        instrument_id: InstrumentId,
596        rates: MakerTakerFeeRates,
597    ) -> anyhow::Result<()> {
598        check_fee_rate(rates.maker, "maker_rate")?;
599        check_fee_rate(rates.taker, "taker_rate")?;
600        self.schedule.set_override(instrument_id, rates);
601        Ok(())
602    }
603
604    /// Returns the owned fee schedule.
605    #[must_use]
606    pub fn schedule(&self) -> &MakerTakerFeeSchedule {
607        &self.schedule
608    }
609}
610
611impl FeeModel for TieredNotionalOptionFeeModel {
612    fn get_commission(
613        &self,
614        order: &OrderAny,
615        fill_quantity: Quantity,
616        fill_px: Price,
617        instrument: &InstrumentAny,
618    ) -> anyhow::Result<Money> {
619        check_option_instrument(instrument, "TieredNotionalOptionFeeModel")?;
620        let liquidity_side = order
621            .liquidity_side()
622            .ok_or_else(|| anyhow::anyhow!("Liquidity side not set"))?;
623        if liquidity_side == LiquiditySide::NoLiquiditySide {
624            anyhow::bail!("Liquidity side not set");
625        }
626
627        let rate = self.schedule.rate_for(instrument.id(), liquidity_side)?;
628        check_fee_rate(rate, "fee_rate")?;
629        let notional =
630            instrument.try_calculate_notional_value(fill_quantity, fill_px, Some(false))?;
631        let total = mul_checked(notional.as_decimal(), rate)?;
632        Money::from_decimal(total, notional.currency).map_err(Into::into)
633    }
634}
635
636fn check_fee_rate(rate: Decimal, name: &str) -> anyhow::Result<()> {
637    if rate < Decimal::ZERO {
638        anyhow::bail!("`{name}` must be greater than or equal to zero");
639    }
640    Ok(())
641}
642
643fn check_option_instrument(instrument: &InstrumentAny, model_name: &str) -> anyhow::Result<()> {
644    if !matches!(
645        instrument,
646        InstrumentAny::CryptoOption(_) | InstrumentAny::OptionContract(_)
647    ) {
648        anyhow::bail!("{model_name} requires an option instrument");
649    }
650    Ok(())
651}
652
653fn commission_currency(instrument: &InstrumentAny) -> Currency {
654    if instrument.is_inverse() {
655        instrument.settlement_currency()
656    } else {
657        instrument.quote_currency()
658    }
659}
660
661#[cfg(test)]
662mod tests {
663    use std::{cell::Cell, rc::Rc};
664
665    use nautilus_model::{
666        enums::{LiquiditySide, OrderSide, OrderType},
667        fees::MakerTakerFeeRates,
668        identifiers::InstrumentId,
669        instruments::{
670            BinaryOption, CryptoOption, Instrument, InstrumentAny, OptionContract,
671            stubs::{
672                audusd_sim, binary_option, crypto_option_btc_deribit, option_contract_appl,
673                option_spread,
674            },
675        },
676        orders::{
677            Order, OrderAny,
678            builder::OrderTestBuilder,
679            stubs::{TestOrderEventStubs, TestOrderStubs},
680        },
681        types::{Currency, Money, Price, Quantity},
682    };
683    use rstest::rstest;
684    use rust_decimal::Decimal;
685    use rust_decimal_macros::dec;
686
687    use super::{
688        CappedOptionFeeModel, FeeModel, FeeModelAny, FeeModelHandle, FixedFeeModel,
689        MakerTakerFeeModel, PerContractFeeModel, ProbabilityPriceFeeModel,
690        TieredNotionalOptionFeeModel,
691    };
692
693    #[rstest]
694    fn test_fixed_model_single_fill() {
695        let expected_commission = Money::new(1.0, Currency::USD());
696        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
697        let fee_model = FixedFeeModel::new(expected_commission, None).unwrap();
698        let market_order = OrderTestBuilder::new(OrderType::Market)
699            .instrument_id(aud_usd.id())
700            .side(OrderSide::Buy)
701            .quantity(Quantity::from(100_000))
702            .build();
703        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
704        let commission = fee_model
705            .get_commission(
706                &accepted_order,
707                Quantity::from(100_000),
708                Price::from("1.0"),
709                &aud_usd,
710            )
711            .unwrap();
712        assert_eq!(commission, expected_commission);
713    }
714
715    #[rstest]
716    #[case(OrderSide::Buy, true, Money::from("1 USD"), Money::from("0 USD"))]
717    #[case(OrderSide::Sell, true, Money::from("1 USD"), Money::from("0 USD"))]
718    #[case(OrderSide::Buy, false, Money::from("1 USD"), Money::from("1 USD"))]
719    #[case(OrderSide::Sell, false, Money::from("1 USD"), Money::from("1 USD"))]
720    fn test_fixed_model_multiple_fills(
721        #[case] order_side: OrderSide,
722        #[case] charge_commission_once: bool,
723        #[case] expected_first_fill: Money,
724        #[case] expected_next_fill: Money,
725    ) {
726        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
727        let fee_model =
728            FixedFeeModel::new(expected_first_fill, Some(charge_commission_once)).unwrap();
729        let market_order = OrderTestBuilder::new(OrderType::Market)
730            .instrument_id(aud_usd.id())
731            .side(order_side)
732            .quantity(Quantity::from(100_000))
733            .build();
734        let mut accepted_order = TestOrderStubs::make_accepted_order(&market_order);
735        let commission_first_fill = fee_model
736            .get_commission(
737                &accepted_order,
738                Quantity::from(50_000),
739                Price::from("1.0"),
740                &aud_usd,
741            )
742            .unwrap();
743        let fill = TestOrderEventStubs::filled(
744            &accepted_order,
745            &aud_usd,
746            None,
747            None,
748            None,
749            Some(Quantity::from(50_000)),
750            None,
751            None,
752            None,
753            None,
754        );
755        accepted_order.apply(fill).unwrap();
756        let commission_next_fill = fee_model
757            .get_commission(
758                &accepted_order,
759                Quantity::from(50_000),
760                Price::from("1.0"),
761                &aud_usd,
762            )
763            .unwrap();
764        assert_eq!(commission_first_fill, expected_first_fill);
765        assert_eq!(commission_next_fill, expected_next_fill);
766    }
767
768    #[rstest]
769    fn test_maker_taker_fee_model_maker_commission() {
770        let fee_model = MakerTakerFeeModel::new(dec!(0.00002), dec!(0.00002));
771        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
772        let maker_fee = dec!(0.00002);
773        let price = Price::from("1.0");
774        let limit_order = OrderTestBuilder::new(OrderType::Limit)
775            .instrument_id(aud_usd.id())
776            .side(OrderSide::Sell)
777            .price(price)
778            .quantity(Quantity::from(100_000))
779            .build();
780        let fill = TestOrderStubs::make_filled_order(&limit_order, &aud_usd, LiquiditySide::Maker);
781        let expected_commission = fill.quantity().as_decimal() * price.as_decimal() * maker_fee;
782        let commission = fee_model
783            .get_commission(&fill, Quantity::from(100_000), Price::from("1.0"), &aud_usd)
784            .unwrap();
785        assert_eq!(commission.as_decimal(), expected_commission);
786    }
787
788    #[rstest]
789    fn test_maker_taker_fee_model_same_instrument_two_schedules() {
790        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
791        let schedule_a = MakerTakerFeeModel::new(dec!(0.0001), dec!(0.0002));
792        let schedule_b = MakerTakerFeeModel::new(dec!(0.0003), dec!(0.0004));
793        let order = OrderTestBuilder::new(OrderType::Market)
794            .instrument_id(instrument.id())
795            .side(OrderSide::Buy)
796            .quantity(Quantity::from(100_000))
797            .build();
798        let fill = TestOrderStubs::make_filled_order(&order, &instrument, LiquiditySide::Taker);
799
800        let commission_a = schedule_a
801            .get_commission(
802                &fill,
803                Quantity::from(100_000),
804                Price::from("1.0"),
805                &instrument,
806            )
807            .unwrap();
808        let commission_b = schedule_b
809            .get_commission(
810                &fill,
811                Quantity::from(100_000),
812                Price::from("1.0"),
813                &instrument,
814            )
815            .unwrap();
816
817        assert_eq!(commission_a, Money::from("20 USD"));
818        assert_eq!(commission_b, Money::from("40 USD"));
819    }
820
821    #[rstest]
822    fn test_maker_taker_fee_model_negative_maker_rate_is_rebate() {
823        let fee_model = MakerTakerFeeModel::new(dec!(-0.00025), dec!(0.00075));
824        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
825        let order = OrderTestBuilder::new(OrderType::Limit)
826            .instrument_id(instrument.id())
827            .side(OrderSide::Sell)
828            .price(Price::from("1.0"))
829            .quantity(Quantity::from(100_000))
830            .build();
831        let fill = TestOrderStubs::make_filled_order(&order, &instrument, LiquiditySide::Maker);
832
833        let commission = fee_model
834            .get_commission(
835                &fill,
836                Quantity::from(100_000),
837                Price::from("1.0"),
838                &instrument,
839            )
840            .unwrap();
841
842        assert_eq!(commission, Money::from("-25 USD"));
843    }
844
845    #[rstest]
846    fn test_maker_taker_fee_model_uses_decimal_rounding() {
847        let fee_model = MakerTakerFeeModel::new(dec!(0.00002), dec!(0.00002));
848        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
849        let price = Price::from("1.0");
850        let quantity = Quantity::from("117250");
851        let limit_order = OrderTestBuilder::new(OrderType::Limit)
852            .instrument_id(aud_usd.id())
853            .side(OrderSide::Sell)
854            .price(price)
855            .quantity(quantity)
856            .build();
857        let fill = TestOrderStubs::make_filled_order(&limit_order, &aud_usd, LiquiditySide::Maker);
858
859        let commission = fee_model
860            .get_commission(&fill, quantity, price, &aud_usd)
861            .unwrap();
862
863        assert_eq!(commission, Money::from("2.34 USD"));
864    }
865
866    #[rstest]
867    fn test_per_contract_fee_model_decimal_overflow_returns_error() {
868        let commission = Money::from("9000000000 USD");
869        let fee_model = PerContractFeeModel::new(commission).unwrap();
870        let mut spread = option_spread();
871        spread.id = InstrumentId::from("((1000000000))SPY C410___(1)SPY C400.SMART");
872        let instrument = InstrumentAny::OptionSpread(spread);
873        let market_order = OrderTestBuilder::new(OrderType::Market)
874            .instrument_id(instrument.id())
875            .side(OrderSide::Buy)
876            .quantity(Quantity::from("9000000000"))
877            .build();
878        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
879        let result = fee_model.get_commission(
880            &accepted_order,
881            Quantity::from("9000000000"),
882            Price::from("1.0"),
883            &instrument,
884        );
885        assert_eq!(
886            result.unwrap_err().to_string(),
887            "commission calculation overflow"
888        );
889    }
890
891    #[rstest]
892    fn test_maker_taker_fee_model_decimal_overflow_returns_error() {
893        let fee_model = MakerTakerFeeModel::new(Decimal::MAX, dec!(0.00002));
894        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
895        let order = OrderTestBuilder::new(OrderType::Limit)
896            .instrument_id(instrument.id())
897            .side(OrderSide::Sell)
898            .price(Price::from("1.0"))
899            .quantity(Quantity::from("2"))
900            .build();
901        let fill = TestOrderStubs::make_filled_order(&order, &instrument, LiquiditySide::Maker);
902
903        let result =
904            fee_model.get_commission(&fill, Quantity::from("2"), Price::from("1.0"), &instrument);
905
906        assert_eq!(
907            result.unwrap_err().to_string(),
908            "commission calculation overflow"
909        );
910    }
911
912    #[rstest]
913    fn test_maker_taker_fee_model_taker_commission() {
914        let fee_model = MakerTakerFeeModel::new(dec!(0.00002), dec!(0.00002));
915        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
916        let taker_fee = dec!(0.00002);
917        let price = Price::from("1.0");
918        let limit_order = OrderTestBuilder::new(OrderType::Limit)
919            .instrument_id(aud_usd.id())
920            .side(OrderSide::Sell)
921            .price(price)
922            .quantity(Quantity::from(100_000))
923            .build();
924
925        let fill = TestOrderStubs::make_filled_order(&limit_order, &aud_usd, LiquiditySide::Taker);
926        let expected_commission = fill.quantity().as_decimal() * price.as_decimal() * taker_fee;
927        let commission = fee_model
928            .get_commission(&fill, Quantity::from(100_000), Price::from("1.0"), &aud_usd)
929            .unwrap();
930        assert_eq!(commission.as_decimal(), expected_commission);
931    }
932
933    #[rstest]
934    fn test_per_contract_fee_model() {
935        let commission_per_contract = Money::new(0.50, Currency::USD());
936        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
937        let fee_model = PerContractFeeModel::new(commission_per_contract).unwrap();
938        let market_order = OrderTestBuilder::new(OrderType::Market)
939            .instrument_id(aud_usd.id())
940            .side(OrderSide::Buy)
941            .quantity(Quantity::from(100))
942            .build();
943        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
944        let commission = fee_model
945            .get_commission(
946                &accepted_order,
947                Quantity::from(100),
948                Price::from("1.0"),
949                &aud_usd,
950            )
951            .unwrap();
952        assert_eq!(commission, Money::new(50.0, Currency::USD()));
953    }
954
955    #[rstest]
956    fn test_per_contract_fee_model_non_spread_symbol_with_separator_charges_one_contract() {
957        let commission_per_contract = Money::from("1.25 USD");
958        let fee_model = PerContractFeeModel::new(commission_per_contract).unwrap();
959        let mut aud_usd = audusd_sim();
960        aud_usd.id = InstrumentId::from("AUD___USD.SIM");
961        let instrument = InstrumentAny::CurrencyPair(aud_usd);
962        let market_order = OrderTestBuilder::new(OrderType::Market)
963            .instrument_id(instrument.id())
964            .side(OrderSide::Buy)
965            .quantity(Quantity::from(2))
966            .build();
967        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
968
969        let commission = fee_model
970            .get_commission(
971                &accepted_order,
972                Quantity::from(2),
973                Price::from("1.0"),
974                &instrument,
975            )
976            .unwrap();
977
978        assert_eq!(commission, Money::from("2.50 USD"));
979    }
980
981    #[rstest]
982    fn test_per_contract_fee_model_option_spread_charges_each_contract() {
983        let commission_per_contract = Money::from("1.25 USD");
984        let fee_model = PerContractFeeModel::new(commission_per_contract).unwrap();
985        let spread_id = InstrumentId::from("((2))SPY C410___(1)SPY C400.SMART");
986        let mut option_spread = option_spread();
987        option_spread.id = spread_id;
988        let instrument = InstrumentAny::OptionSpread(option_spread);
989        let market_order = OrderTestBuilder::new(OrderType::Market)
990            .instrument_id(instrument.id())
991            .side(OrderSide::Buy)
992            .quantity(Quantity::from(2))
993            .build();
994        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
995
996        let commission = fee_model
997            .get_commission(
998                &accepted_order,
999                Quantity::from(2),
1000                Price::from("1.0"),
1001                &instrument,
1002            )
1003            .unwrap();
1004
1005        assert_eq!(commission, Money::from("7.50 USD"));
1006    }
1007
1008    #[rstest]
1009    fn test_per_contract_fee_model_non_generic_option_spread_charges_one_contract() {
1010        let commission_per_contract = Money::from("1.25 USD");
1011        let fee_model = PerContractFeeModel::new(commission_per_contract).unwrap();
1012        let instrument = InstrumentAny::OptionSpread(option_spread());
1013        let market_order = OrderTestBuilder::new(OrderType::Market)
1014            .instrument_id(instrument.id())
1015            .side(OrderSide::Buy)
1016            .quantity(Quantity::from(2))
1017            .build();
1018        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
1019
1020        let commission = fee_model
1021            .get_commission(
1022                &accepted_order,
1023                Quantity::from(2),
1024                Price::from("1.0"),
1025                &instrument,
1026            )
1027            .unwrap();
1028
1029        assert_eq!(commission, Money::from("2.50 USD"));
1030    }
1031
1032    #[rstest]
1033    fn test_per_contract_fee_model_malformed_generic_spread_fails() {
1034        let commission_per_contract = Money::from("1.25 USD");
1035        let fee_model = PerContractFeeModel::new(commission_per_contract).unwrap();
1036        let spread_id = InstrumentId::from("(1)SPY C400___SPY C410.SMART");
1037        let mut option_spread = option_spread();
1038        option_spread.id = spread_id;
1039        let instrument = InstrumentAny::OptionSpread(option_spread);
1040        let market_order = OrderTestBuilder::new(OrderType::Market)
1041            .instrument_id(instrument.id())
1042            .side(OrderSide::Buy)
1043            .quantity(Quantity::from(2))
1044            .build();
1045        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
1046
1047        let result = fee_model.get_commission(
1048            &accepted_order,
1049            Quantity::from(2),
1050            Price::from("1.0"),
1051            &instrument,
1052        );
1053
1054        assert_eq!(
1055            result.unwrap_err().to_string(),
1056            "Invalid generic spread leg component: SPY C410"
1057        );
1058    }
1059
1060    #[rstest]
1061    fn test_per_contract_fee_model_generic_spread_contract_count_overflow_fails() {
1062        let commission_per_contract = Money::from("1.25 USD");
1063        let fee_model = PerContractFeeModel::new(commission_per_contract).unwrap();
1064        let max_ratio = i64::MAX;
1065        let spread_symbol = format!("({max_ratio})SPY C400___({max_ratio})SPY C410");
1066        let spread_id = InstrumentId::from(format!("{spread_symbol}.SMART"));
1067        let mut option_spread = option_spread();
1068        option_spread.id = spread_id;
1069        let instrument = InstrumentAny::OptionSpread(option_spread);
1070        let market_order = OrderTestBuilder::new(OrderType::Market)
1071            .instrument_id(instrument.id())
1072            .side(OrderSide::Buy)
1073            .quantity(Quantity::from(2))
1074            .build();
1075        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
1076
1077        let result = fee_model.get_commission(
1078            &accepted_order,
1079            Quantity::from(2),
1080            Price::from("1.0"),
1081            &instrument,
1082        );
1083
1084        assert_eq!(
1085            result.unwrap_err().to_string(),
1086            format!("Generic spread contract count overflowed for {spread_symbol}")
1087        );
1088    }
1089
1090    #[rstest]
1091    fn test_per_contract_fee_model_partial_fill() {
1092        let commission_per_contract = Money::new(1.25, Currency::USD());
1093        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
1094        let fee_model = PerContractFeeModel::new(commission_per_contract).unwrap();
1095        let market_order = OrderTestBuilder::new(OrderType::Market)
1096            .instrument_id(aud_usd.id())
1097            .side(OrderSide::Sell)
1098            .quantity(Quantity::from(1000))
1099            .build();
1100        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
1101        let commission = fee_model
1102            .get_commission(
1103                &accepted_order,
1104                Quantity::from(400),
1105                Price::from("1.0"),
1106                &aud_usd,
1107            )
1108            .unwrap();
1109        assert_eq!(commission, Money::new(500.0, Currency::USD()));
1110    }
1111
1112    #[rstest]
1113    fn test_per_contract_fee_model_uses_decimal_rounding() {
1114        let commission_per_contract = Money::from("0.50 USD");
1115        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
1116        let fee_model = PerContractFeeModel::new(commission_per_contract).unwrap();
1117        let market_order = OrderTestBuilder::new(OrderType::Market)
1118            .instrument_id(aud_usd.id())
1119            .side(OrderSide::Buy)
1120            .quantity(Quantity::from("5"))
1121            .build();
1122        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
1123
1124        let commission = fee_model
1125            .get_commission(
1126                &accepted_order,
1127                Quantity::from("4.69"),
1128                Price::from("1.0"),
1129                &aud_usd,
1130            )
1131            .unwrap();
1132
1133        assert_eq!(commission, Money::from("2.34 USD"));
1134    }
1135
1136    #[rstest]
1137    fn test_per_contract_fee_model_negative_commission_fails() {
1138        let result = PerContractFeeModel::new(Money::new(-1.0, Currency::USD()));
1139
1140        assert_eq!(
1141            result.unwrap_err().to_string(),
1142            "Commission must be greater than or equal to zero"
1143        );
1144    }
1145
1146    #[rstest]
1147    #[case::crypto_p97("0.072", "0.970", "0.00210")]
1148    #[case::sports_p50("0.03", "0.500", "0.00750")]
1149    #[case::sports_p30("0.03", "0.300", "0.00630")]
1150    fn test_probability_price_fee_model_taker_commission(
1151        binary_option: BinaryOption,
1152        #[case] taker_fee: &str,
1153        #[case] price: &str,
1154        #[case] expected: &str,
1155    ) {
1156        let instrument = InstrumentAny::BinaryOption(binary_option);
1157        let fill = binary_option_fill_order(&instrument, LiquiditySide::Taker, price);
1158
1159        let fee_model = ProbabilityPriceFeeModel::new(
1160            Decimal::ZERO,
1161            Decimal::from_str_exact(taker_fee).unwrap(),
1162        );
1163
1164        let commission = fee_model
1165            .get_commission(
1166                &fill,
1167                Quantity::from("1.00"),
1168                Price::from(price),
1169                &instrument,
1170            )
1171            .unwrap();
1172
1173        assert_eq!(commission.currency, Currency::USDC());
1174        assert_eq!(
1175            commission.as_decimal(),
1176            Decimal::from_str_exact(expected).unwrap()
1177        );
1178    }
1179
1180    #[rstest]
1181    fn test_probability_price_fee_model_maker_commission_uses_explicit_rate(
1182        binary_option: BinaryOption,
1183    ) {
1184        let instrument = InstrumentAny::BinaryOption(binary_option);
1185        let fill = binary_option_fill_order(&instrument, LiquiditySide::Maker, "0.500");
1186        let fee_model =
1187            FeeModelAny::ProbabilityPrice(ProbabilityPriceFeeModel::new(dec!(0.01), dec!(0.02)));
1188
1189        let commission = fee_model
1190            .get_commission(
1191                &fill,
1192                Quantity::from("1.00"),
1193                Price::from("0.500"),
1194                &instrument,
1195            )
1196            .unwrap();
1197
1198        assert_eq!(commission, Money::from("0.00250 USDC"));
1199    }
1200
1201    #[rstest]
1202    fn test_probability_price_fee_model_uses_instrument_override(binary_option: BinaryOption) {
1203        let instrument = InstrumentAny::BinaryOption(binary_option);
1204        let fill = binary_option_fill_order(&instrument, LiquiditySide::Taker, "0.500");
1205        let mut fee_model = ProbabilityPriceFeeModel::new(dec!(0.01), dec!(0.02));
1206        let default_commission = fee_model
1207            .get_commission(
1208                &fill,
1209                Quantity::from("1.00"),
1210                Price::from("0.500"),
1211                &instrument,
1212            )
1213            .unwrap();
1214        fee_model.set_override(
1215            instrument.id(),
1216            MakerTakerFeeRates::new(dec!(0.03), dec!(0.04)),
1217        );
1218
1219        let override_commission = fee_model
1220            .get_commission(
1221                &fill,
1222                Quantity::from("1.00"),
1223                Price::from("0.500"),
1224                &instrument,
1225            )
1226            .unwrap();
1227
1228        assert_eq!(default_commission, Money::from("0.005 USDC"));
1229        assert_eq!(override_commission, Money::from("0.010 USDC"));
1230    }
1231
1232    #[rstest]
1233    fn test_probability_price_fee_model_decimal_overflow_returns_error(
1234        binary_option: BinaryOption,
1235    ) {
1236        let instrument = InstrumentAny::BinaryOption(binary_option);
1237        let fill = binary_option_fill_order(&instrument, LiquiditySide::Maker, "0.500");
1238        let fee_model = ProbabilityPriceFeeModel::new(Decimal::MAX, dec!(0.02));
1239
1240        let result = fee_model.get_commission(
1241            &fill,
1242            Quantity::from("5.00"),
1243            Price::from("0.500"),
1244            &instrument,
1245        );
1246
1247        assert_eq!(
1248            result.unwrap_err().to_string(),
1249            "commission calculation overflow"
1250        );
1251    }
1252
1253    #[rstest]
1254    fn test_fee_model_handle_calls_custom_model_without_model_clone() {
1255        let calls = Rc::new(Cell::new(0));
1256        let expected_commission = Money::from("1.23 USD");
1257        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
1258        let market_order = OrderTestBuilder::new(OrderType::Market)
1259            .instrument_id(aud_usd.id())
1260            .side(OrderSide::Buy)
1261            .quantity(Quantity::from(100_000))
1262            .build();
1263        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
1264        let fee_model = FeeModelHandle::new(CountingFeeModel {
1265            calls: Rc::clone(&calls),
1266            commission: expected_commission,
1267        });
1268        let cloned_fee_model = fee_model.clone();
1269        drop(fee_model);
1270
1271        let commission = cloned_fee_model
1272            .get_commission(
1273                &accepted_order,
1274                Quantity::from(100_000),
1275                Price::from("1.0"),
1276                &aud_usd,
1277            )
1278            .unwrap();
1279
1280        assert_eq!(calls.get(), 1);
1281        assert_eq!(commission, expected_commission);
1282    }
1283
1284    #[rstest]
1285    fn test_fee_model_handle_from_rc_calls_custom_model() {
1286        let calls = Rc::new(Cell::new(0));
1287        let expected_commission = Money::from("1.23 USD");
1288        let aud_usd = InstrumentAny::CurrencyPair(audusd_sim());
1289        let market_order = OrderTestBuilder::new(OrderType::Market)
1290            .instrument_id(aud_usd.id())
1291            .side(OrderSide::Buy)
1292            .quantity(Quantity::from(100_000))
1293            .build();
1294        let accepted_order = TestOrderStubs::make_accepted_order(&market_order);
1295        let model = Rc::new(CountingFeeModel {
1296            calls: Rc::clone(&calls),
1297            commission: expected_commission,
1298        });
1299        let fee_model = FeeModelHandle::from_rc(model);
1300
1301        let commission = fee_model
1302            .get_commission(
1303                &accepted_order,
1304                Quantity::from(100_000),
1305                Price::from("1.0"),
1306                &aud_usd,
1307            )
1308            .unwrap();
1309
1310        assert_eq!(calls.get(), 1);
1311        assert_eq!(commission, expected_commission);
1312    }
1313
1314    struct CountingFeeModel {
1315        calls: Rc<Cell<u32>>,
1316        commission: Money,
1317    }
1318
1319    impl FeeModel for CountingFeeModel {
1320        fn get_commission(
1321            &self,
1322            _order: &OrderAny,
1323            _fill_quantity: Quantity,
1324            _fill_px: Price,
1325            _instrument: &InstrumentAny,
1326        ) -> anyhow::Result<Money> {
1327            self.calls.set(self.calls.get() + 1);
1328            Ok(self.commission)
1329        }
1330    }
1331
1332    #[rstest]
1333    fn test_probability_price_fee_model_rejects_non_binary_instrument() {
1334        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1335        let fill = binary_option_fill_order(&instrument, LiquiditySide::Taker, "0.500");
1336        let fee_model = ProbabilityPriceFeeModel::new(dec!(0.01), dec!(0.02));
1337
1338        let result = fee_model.get_commission(
1339            &fill,
1340            Quantity::from("1.00"),
1341            Price::from("0.500"),
1342            &instrument,
1343        );
1344
1345        assert_eq!(
1346            result.unwrap_err().to_string(),
1347            "ProbabilityPriceFeeModel requires a binary option instrument"
1348        );
1349    }
1350
1351    #[rstest]
1352    #[case::negative("-0.001")]
1353    #[case::above_one("1.5")]
1354    fn test_probability_price_fee_model_rejects_fill_price_out_of_range(
1355        binary_option: BinaryOption,
1356        #[case] price: &str,
1357    ) {
1358        let instrument = InstrumentAny::BinaryOption(binary_option);
1359        let fill = binary_option_fill_order(&instrument, LiquiditySide::Taker, "0.500");
1360        let fee_model = ProbabilityPriceFeeModel::new(dec!(0.01), dec!(0.02));
1361
1362        let result = fee_model.get_commission(
1363            &fill,
1364            Quantity::from("1.00"),
1365            Price::from(price),
1366            &instrument,
1367        );
1368
1369        assert_eq!(
1370            result.unwrap_err().to_string(),
1371            "ProbabilityPriceFeeModel requires a fill price in [0, 1]"
1372        );
1373    }
1374
1375    #[rstest]
1376    #[case::zero("0.000")]
1377    #[case::one("1.000")]
1378    fn test_probability_price_fee_model_boundary_prices_have_zero_commission(
1379        binary_option: BinaryOption,
1380        #[case] price: &str,
1381    ) {
1382        let instrument = InstrumentAny::BinaryOption(binary_option);
1383        let fill = binary_option_fill_order(&instrument, LiquiditySide::Taker, price);
1384        let fee_model = ProbabilityPriceFeeModel::new(dec!(0.01), dec!(0.02));
1385
1386        let commission = fee_model
1387            .get_commission(
1388                &fill,
1389                Quantity::from("1.00"),
1390                Price::from(price),
1391                &instrument,
1392            )
1393            .unwrap();
1394
1395        assert_eq!(commission, Money::zero(Currency::USDC()));
1396    }
1397
1398    #[rstest]
1399    #[case::maker(dec!(-0.0001), dec!(0.0003), None, "maker_rate")]
1400    #[case::taker(dec!(0.0001), dec!(-0.0003), None, "taker_rate")]
1401    #[case::cap(dec!(0.0001), dec!(0.0003), Some(dec!(-0.125)), "cap_rate")]
1402    fn test_capped_option_fee_model_negative_rate_fails(
1403        #[case] maker_rate: Decimal,
1404        #[case] taker_rate: Decimal,
1405        #[case] cap_rate: Option<Decimal>,
1406        #[case] expected_field: &str,
1407    ) {
1408        let result = CappedOptionFeeModel::new(maker_rate, taker_rate, cap_rate);
1409
1410        assert_eq!(
1411            result.unwrap_err().to_string(),
1412            format!("`{expected_field}` must be greater than or equal to zero")
1413        );
1414    }
1415
1416    #[rstest]
1417    #[case::capped(FeeModelAny::CappedOption(
1418        CappedOptionFeeModel::new(Decimal::ZERO, Decimal::ZERO, Some(Decimal::ZERO)).unwrap(),
1419    ))]
1420    #[case::tiered(FeeModelAny::TieredNotionalOption(
1421        TieredNotionalOptionFeeModel::new(Decimal::ZERO, Decimal::ZERO).unwrap(),
1422    ))]
1423    fn test_option_fee_models_allow_zero_rates(
1424        crypto_option_btc_deribit: CryptoOption,
1425        #[case] fee_model: FeeModelAny,
1426    ) {
1427        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1428        let fill = option_fill_order(&instrument, LiquiditySide::Taker);
1429
1430        let commission = fee_model
1431            .get_commission_with_context(
1432                &fill,
1433                Quantity::from("2.0"),
1434                Price::from("100.00"),
1435                &instrument,
1436                Some(Price::from("50000.00")),
1437            )
1438            .unwrap();
1439
1440        assert_eq!(commission, Money::zero(Currency::USD()));
1441    }
1442
1443    #[rstest]
1444    fn test_capped_option_fee_model_maker_commission_rate_bound(
1445        crypto_option_btc_deribit: CryptoOption,
1446    ) {
1447        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1448        let fill = option_fill_order(&instrument, LiquiditySide::Maker);
1449        let fee_model = FeeModelAny::CappedOption(
1450            CappedOptionFeeModel::new(dec!(0.0001), dec!(0.0003), None).unwrap(),
1451        );
1452
1453        let commission = fee_model
1454            .get_commission_with_context(
1455                &fill,
1456                Quantity::from("2.0"),
1457                Price::from("100.00"),
1458                &instrument,
1459                Some(Price::from("50000.00")),
1460            )
1461            .unwrap();
1462
1463        assert_eq!(commission.currency, Currency::USD());
1464        assert_eq!(commission.as_decimal(), dec!(10.00));
1465    }
1466
1467    #[rstest]
1468    fn test_capped_option_fee_model_uses_instrument_override(
1469        crypto_option_btc_deribit: CryptoOption,
1470    ) {
1471        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1472        let fill = option_fill_order(&instrument, LiquiditySide::Maker);
1473        let mut fee_model = CappedOptionFeeModel::new(dec!(0.0001), dec!(0.0003), None).unwrap();
1474        let default_commission = fee_model
1475            .get_commission_with_context(
1476                &fill,
1477                Quantity::from("2.0"),
1478                Price::from("100.00"),
1479                &instrument,
1480                Some(Price::from("50000.00")),
1481            )
1482            .unwrap();
1483        fee_model
1484            .set_override(
1485                instrument.id(),
1486                MakerTakerFeeRates::new(dec!(0.0002), dec!(0.0004)),
1487            )
1488            .unwrap();
1489
1490        let override_commission = fee_model
1491            .get_commission_with_context(
1492                &fill,
1493                Quantity::from("2.0"),
1494                Price::from("100.00"),
1495                &instrument,
1496                Some(Price::from("50000.00")),
1497            )
1498            .unwrap();
1499
1500        assert_eq!(default_commission, Money::from("10 USD"));
1501        assert_eq!(override_commission, Money::from("20 USD"));
1502    }
1503
1504    #[rstest]
1505    #[case::maker(dec!(-0.0002), dec!(0.0004), "maker_rate")]
1506    #[case::taker(dec!(0.0002), dec!(-0.0004), "taker_rate")]
1507    fn test_capped_option_fee_model_rejects_negative_override(
1508        crypto_option_btc_deribit: CryptoOption,
1509        #[case] maker_rate: Decimal,
1510        #[case] taker_rate: Decimal,
1511        #[case] expected_field: &str,
1512    ) {
1513        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1514        let mut fee_model = CappedOptionFeeModel::new(dec!(0.0001), dec!(0.0003), None).unwrap();
1515
1516        let result = fee_model.set_override(
1517            instrument.id(),
1518            MakerTakerFeeRates::new(maker_rate, taker_rate),
1519        );
1520
1521        assert_eq!(
1522            result.unwrap_err().to_string(),
1523            format!("`{expected_field}` must be greater than or equal to zero")
1524        );
1525    }
1526
1527    #[rstest]
1528    fn test_capped_option_fee_model_decimal_overflow_returns_error(
1529        crypto_option_btc_deribit: CryptoOption,
1530    ) {
1531        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1532        let fill = option_fill_order(&instrument, LiquiditySide::Maker);
1533        let fee_model = CappedOptionFeeModel::new(Decimal::MAX, dec!(0.0003), None).unwrap();
1534
1535        let result = fee_model.get_commission_with_context(
1536            &fill,
1537            Quantity::from("2.0"),
1538            Price::from("100.00"),
1539            &instrument,
1540            Some(Price::from("50000.00")),
1541        );
1542
1543        assert_eq!(
1544            result.unwrap_err().to_string(),
1545            "commission calculation overflow"
1546        );
1547    }
1548
1549    #[rstest]
1550    fn test_capped_option_fee_model_taker_commission_cap_bound(
1551        crypto_option_btc_deribit: CryptoOption,
1552    ) {
1553        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1554        let fill = option_fill_order(&instrument, LiquiditySide::Taker);
1555        let fee_model = CappedOptionFeeModel::new(dec!(0.0001), dec!(0.0003), None).unwrap();
1556
1557        let commission = fee_model
1558            .get_commission_with_context(
1559                &fill,
1560                Quantity::from("2.0"),
1561                Price::from("10.00"),
1562                &instrument,
1563                Some(Price::from("50000.00")),
1564            )
1565            .unwrap();
1566
1567        assert_eq!(commission.currency, Currency::USD());
1568        assert_eq!(commission.as_decimal(), dec!(2.50));
1569    }
1570
1571    #[rstest]
1572    fn test_capped_option_fee_model_applies_contract_multiplier(
1573        mut option_contract_appl: OptionContract,
1574    ) {
1575        option_contract_appl.multiplier = Quantity::from(100);
1576        let instrument = InstrumentAny::OptionContract(option_contract_appl);
1577        let fill = option_fill_order(&instrument, LiquiditySide::Maker);
1578        let fee_model = CappedOptionFeeModel::new(dec!(0.0001), dec!(0.0003), None).unwrap();
1579
1580        let commission = fee_model
1581            .get_commission_with_context(
1582                &fill,
1583                Quantity::from("2"),
1584                Price::from("2.00"),
1585                &instrument,
1586                Some(Price::from("150.00")),
1587            )
1588            .unwrap();
1589
1590        assert_eq!(commission.currency, Currency::USD());
1591        assert_eq!(commission.as_decimal(), dec!(3.00));
1592    }
1593
1594    #[rstest]
1595    fn test_capped_option_fee_model_inverse_commission_uses_settlement_currency(
1596        mut crypto_option_btc_deribit: CryptoOption,
1597    ) {
1598        crypto_option_btc_deribit.is_inverse = true;
1599        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1600        let fill = option_fill_order(&instrument, LiquiditySide::Taker);
1601        let fee_model = CappedOptionFeeModel::new(dec!(0.0001), dec!(0.0003), None).unwrap();
1602
1603        let commission = fee_model
1604            .get_commission(
1605                &fill,
1606                Quantity::from("2.0"),
1607                Price::from("0.010"),
1608                &instrument,
1609            )
1610            .unwrap();
1611
1612        assert_eq!(commission.currency, Currency::BTC());
1613        assert_eq!(commission.as_decimal(), dec!(0.0006));
1614    }
1615
1616    #[rstest]
1617    fn test_capped_option_fee_model_requires_underlying_price(
1618        crypto_option_btc_deribit: CryptoOption,
1619    ) {
1620        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1621        let fill = option_fill_order(&instrument, LiquiditySide::Taker);
1622        let fee_model = CappedOptionFeeModel::new(dec!(0.0001), dec!(0.0003), None).unwrap();
1623
1624        let result = fee_model.get_commission(
1625            &fill,
1626            Quantity::from("1.0"),
1627            Price::from("10.00"),
1628            &instrument,
1629        );
1630
1631        assert_eq!(
1632            result.unwrap_err().to_string(),
1633            "Underlying price is required"
1634        );
1635    }
1636
1637    #[rstest]
1638    fn test_capped_option_fee_model_rejects_non_option_instrument() {
1639        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1640        let fill = option_fill_order(&instrument, LiquiditySide::Taker);
1641        let fee_model = CappedOptionFeeModel::new(dec!(0.0001), dec!(0.0003), None).unwrap();
1642
1643        let result = fee_model.get_commission_with_context(
1644            &fill,
1645            Quantity::from("1.0"),
1646            Price::from("10.00"),
1647            &instrument,
1648            Some(Price::from("50000.00")),
1649        );
1650
1651        assert_eq!(
1652            result.unwrap_err().to_string(),
1653            "CappedOptionFeeModel requires an option instrument"
1654        );
1655    }
1656
1657    #[rstest]
1658    #[case::maker(LiquiditySide::Maker, dec!(0.04))]
1659    #[case::taker(LiquiditySide::Taker, dec!(0.10))]
1660    fn test_tiered_notional_option_fee_model_commission(
1661        crypto_option_btc_deribit: CryptoOption,
1662        #[case] liquidity_side: LiquiditySide,
1663        #[case] expected_commission: Decimal,
1664    ) {
1665        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1666        let fill = option_fill_order(&instrument, liquidity_side);
1667        let fee_model = FeeModelAny::TieredNotionalOption(
1668            TieredNotionalOptionFeeModel::new(dec!(0.0002), dec!(0.0005)).unwrap(),
1669        );
1670
1671        let commission = fee_model
1672            .get_commission(
1673                &fill,
1674                Quantity::from("2.0"),
1675                Price::from("100.00"),
1676                &instrument,
1677            )
1678            .unwrap();
1679
1680        assert_eq!(commission.currency, Currency::USD());
1681        assert_eq!(commission.as_decimal(), expected_commission);
1682    }
1683
1684    #[rstest]
1685    fn test_tiered_notional_option_fee_model_uses_instrument_override(
1686        crypto_option_btc_deribit: CryptoOption,
1687    ) {
1688        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1689        let fill = option_fill_order(&instrument, LiquiditySide::Maker);
1690        let mut fee_model = TieredNotionalOptionFeeModel::new(dec!(0.0002), dec!(0.0005)).unwrap();
1691        let default_commission = fee_model
1692            .get_commission(
1693                &fill,
1694                Quantity::from("2.0"),
1695                Price::from("100.00"),
1696                &instrument,
1697            )
1698            .unwrap();
1699        fee_model
1700            .set_override(
1701                instrument.id(),
1702                MakerTakerFeeRates::new(dec!(0.0004), dec!(0.0010)),
1703            )
1704            .unwrap();
1705
1706        let override_commission = fee_model
1707            .get_commission(
1708                &fill,
1709                Quantity::from("2.0"),
1710                Price::from("100.00"),
1711                &instrument,
1712            )
1713            .unwrap();
1714
1715        assert_eq!(default_commission, Money::from("0.04 USD"));
1716        assert_eq!(override_commission, Money::from("0.08 USD"));
1717    }
1718
1719    #[rstest]
1720    fn test_tiered_notional_option_fee_model_decimal_overflow_returns_error(
1721        crypto_option_btc_deribit: CryptoOption,
1722    ) {
1723        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1724        let fill = option_fill_order(&instrument, LiquiditySide::Maker);
1725        let fee_model = TieredNotionalOptionFeeModel::new(Decimal::MAX, dec!(0.0005)).unwrap();
1726
1727        let result = fee_model.get_commission(
1728            &fill,
1729            Quantity::from("2.0"),
1730            Price::from("100.00"),
1731            &instrument,
1732        );
1733
1734        assert_eq!(
1735            result.unwrap_err().to_string(),
1736            "commission calculation overflow"
1737        );
1738    }
1739
1740    #[rstest]
1741    fn test_tiered_notional_option_fee_model_inverse_commission_uses_base_currency(
1742        mut crypto_option_btc_deribit: CryptoOption,
1743    ) {
1744        crypto_option_btc_deribit.is_inverse = true;
1745        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1746        let fill = option_fill_order(&instrument, LiquiditySide::Taker);
1747        let fee_model = TieredNotionalOptionFeeModel::new(dec!(0.0002), dec!(0.0005)).unwrap();
1748
1749        let commission = fee_model
1750            .get_commission(
1751                &fill,
1752                Quantity::from("2.0"),
1753                Price::from("0.010"),
1754                &instrument,
1755            )
1756            .unwrap();
1757
1758        assert_eq!(commission.currency, Currency::BTC());
1759        assert_eq!(commission.as_decimal(), dec!(0.00001));
1760    }
1761
1762    #[rstest]
1763    fn test_tiered_notional_option_fee_model_rejects_non_option_instrument() {
1764        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1765        let fill = option_fill_order(&instrument, LiquiditySide::Taker);
1766        let fee_model = TieredNotionalOptionFeeModel::new(dec!(0.0002), dec!(0.0005)).unwrap();
1767
1768        let result = fee_model.get_commission(
1769            &fill,
1770            Quantity::from("1.0"),
1771            Price::from("10.00"),
1772            &instrument,
1773        );
1774
1775        assert_eq!(
1776            result.unwrap_err().to_string(),
1777            "TieredNotionalOptionFeeModel requires an option instrument"
1778        );
1779    }
1780
1781    #[rstest]
1782    #[case::maker(dec!(-0.0002), dec!(0.0005), "maker_rate")]
1783    #[case::taker(dec!(0.0002), dec!(-0.0005), "taker_rate")]
1784    fn test_tiered_notional_option_fee_model_negative_rate_fails(
1785        #[case] maker_rate: Decimal,
1786        #[case] taker_rate: Decimal,
1787        #[case] expected_field: &str,
1788    ) {
1789        let result = TieredNotionalOptionFeeModel::new(maker_rate, taker_rate);
1790
1791        assert_eq!(
1792            result.unwrap_err().to_string(),
1793            format!("`{expected_field}` must be greater than or equal to zero")
1794        );
1795    }
1796
1797    #[rstest]
1798    #[case::maker(dec!(-0.0004), dec!(0.0010), "maker_rate")]
1799    #[case::taker(dec!(0.0004), dec!(-0.0010), "taker_rate")]
1800    fn test_tiered_notional_option_fee_model_rejects_negative_override(
1801        crypto_option_btc_deribit: CryptoOption,
1802        #[case] maker_rate: Decimal,
1803        #[case] taker_rate: Decimal,
1804        #[case] expected_field: &str,
1805    ) {
1806        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1807        let mut fee_model = TieredNotionalOptionFeeModel::new(dec!(0.0002), dec!(0.0005)).unwrap();
1808
1809        let result = fee_model.set_override(
1810            instrument.id(),
1811            MakerTakerFeeRates::new(maker_rate, taker_rate),
1812        );
1813
1814        assert_eq!(
1815            result.unwrap_err().to_string(),
1816            format!("`{expected_field}` must be greater than or equal to zero")
1817        );
1818    }
1819
1820    #[rstest]
1821    fn test_tiered_notional_option_fee_model_requires_liquidity_side(
1822        crypto_option_btc_deribit: CryptoOption,
1823    ) {
1824        let instrument = InstrumentAny::CryptoOption(crypto_option_btc_deribit);
1825        let order = OrderTestBuilder::new(OrderType::Limit)
1826            .instrument_id(instrument.id())
1827            .side(OrderSide::Buy)
1828            .price(Price::from("100.00"))
1829            .quantity(Quantity::from("2.0"))
1830            .build();
1831        let fee_model = TieredNotionalOptionFeeModel::new(dec!(0.0002), dec!(0.0005)).unwrap();
1832
1833        let result = fee_model.get_commission(
1834            &order,
1835            Quantity::from("1.0"),
1836            Price::from("10.00"),
1837            &instrument,
1838        );
1839
1840        assert_eq!(result.unwrap_err().to_string(), "Liquidity side not set");
1841    }
1842
1843    fn option_fill_order(instrument: &InstrumentAny, liquidity_side: LiquiditySide) -> OrderAny {
1844        let limit_order = OrderTestBuilder::new(OrderType::Limit)
1845            .instrument_id(instrument.id())
1846            .side(OrderSide::Buy)
1847            .price(Price::from("100.00"))
1848            .quantity(Quantity::from("2.0"))
1849            .build();
1850
1851        TestOrderStubs::make_filled_order(&limit_order, instrument, liquidity_side)
1852    }
1853
1854    fn binary_option_fill_order(
1855        instrument: &InstrumentAny,
1856        liquidity_side: LiquiditySide,
1857        price: &str,
1858    ) -> OrderAny {
1859        let limit_order = OrderTestBuilder::new(OrderType::Limit)
1860            .instrument_id(instrument.id())
1861            .side(OrderSide::Buy)
1862            .price(Price::from(price))
1863            .quantity(Quantity::from("1.00"))
1864            .build();
1865
1866        TestOrderStubs::make_filled_order(&limit_order, instrument, liquidity_side)
1867    }
1868}