Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 60 additions & 14 deletions src/exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use crate::{
config::Config,
execution_rules::{
self,
BufferCapacities,
fill_flows,
},
ledger::{
Expand Down Expand Up @@ -79,6 +80,7 @@ use crate::{
TimestampNs,
UserOrderId,
},
utils::reserve_to_capacity,
};

/// Result of submitting a limit order via [`Exchange::submit_limit_order_with_execution`],
Expand Down Expand Up @@ -161,7 +163,7 @@ where
}

/// The main leveraged futures exchange for simulated trading
#[derive(Debug, Clone, Getters, MutGetters)]
#[derive(Debug, Getters, MutGetters)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde",
Expand Down Expand Up @@ -238,6 +240,42 @@ where
order_rate_limiter: OrderRateLimiter,
}

impl<I, const D: u8, BaseOrQuote, UserOrderIdT> Clone for Exchange<I, D, BaseOrQuote, UserOrderIdT>
where
I: Mon<D>,
BaseOrQuote: Currency<I, D>,
BaseOrQuote::PairedCurrency: MarginCurrency<I, D>,
UserOrderIdT: UserOrderId,
{
/// Clone the exchange with the pre-allocated buffers of a freshly constructed one.
///
/// `Vec::clone` keeps only the length, so a derived clone left the event and scratch
/// buffers without spare capacity and the first fill, forced cancel or stop event
/// panicked in `push_within_capacity`. `Clone` is cold, so restoring the bounds costs
/// one allocation per non-empty buffer and keeps every push path free of capacity
/// checks. `PendingStops` retains its own capacity in its `Clone`.
fn clone(&self) -> Self {
let mut cloned = Self {
config: self.config.clone(),
market_state: self.market_state.clone(),
risk_engine: self.risk_engine.clone(),
cross_risk_engine: self.cross_risk_engine.clone(),
next_order_id: self.next_order_id,
account: self.account.clone(),
limit_order_events: self.limit_order_events.clone(),
forced_cancel_scratch: self.forced_cancel_scratch.clone(),
liquidated_during_fills: self.liquidated_during_fills,
pending_stops: self.pending_stops.clone(),
stop_order_events: self.stop_order_events.clone(),
elected_stops_scratch: self.elected_stops_scratch.clone(),
ledger: self.ledger.clone(),
order_rate_limiter: self.order_rate_limiter.clone(),
};
cloned.reserve_preallocated_capacities();
cloned
}
}

impl<I, const D: u8, BaseOrQuote, UserOrderIdT> Exchange<I, D, BaseOrQuote, UserOrderIdT>
where
I: Mon<D>,
Expand All @@ -263,30 +301,38 @@ where
let balances = Balances::new(config.starting_wallet_balance());
let init_margin_req = config.contract_spec().init_margin_req();
let maker_fee = *config.contract_spec().fee_maker().as_ref();
let pending_stops = PendingStops::with_capacity(max_active_orders);
// Every pending stop yields at most one event per public call (it is elected or
// force-cancelled once), and the buffer is cleared at the start of every such call.
let stop_order_events = Vec::with_capacity(usize::from(max_active_orders.get()));
let caps = BufferCapacities::for_order_slots(usize::from(max_active_orders.get()));
Self {
config,
market_state,
risk_engine,
cross_risk_engine,
next_order_id: OrderId::default(),
account: Account::new(balances, max_active_orders, init_margin_req, maker_fee),
// Bids and asks each have a capacity of `max_active_orders`, so one update
// can emit at most `2 * max_active_orders` fills plus as many forced cancels.
limit_order_events: Vec::with_capacity(usize::from(max_active_orders.get()) * 4),
forced_cancel_scratch: Vec::with_capacity(usize::from(max_active_orders.get()) * 2),
limit_order_events: Vec::with_capacity(caps.order_events()),
forced_cancel_scratch: Vec::with_capacity(caps.forced_cancels()),
liquidated_during_fills: false,
pending_stops,
stop_order_events,
elected_stops_scratch: Vec::with_capacity(usize::from(max_active_orders.get())),
pending_stops: PendingStops::with_capacity(max_active_orders),
stop_order_events: Vec::with_capacity(caps.stop_events()),
elected_stops_scratch: Vec::with_capacity(caps.elected_stops()),
ledger: None,
order_rate_limiter,
}
}

/// Give the per-update buffers the capacity of a freshly constructed exchange.
///
/// [`Exchange::new`] allocates them up front, [`Exchange::clone`] restores them after
/// `Vec::clone` dropped the spare capacity. See [`BufferCapacities`].
fn reserve_preallocated_capacities(&mut self) {
let caps =
BufferCapacities::for_order_slots(usize::from(self.config.max_num_open_orders().get()));
reserve_to_capacity(&mut self.limit_order_events, caps.order_events());
reserve_to_capacity(&mut self.forced_cancel_scratch, caps.forced_cancels());
reserve_to_capacity(&mut self.elected_stops_scratch, caps.elected_stops());
reserve_to_capacity(&mut self.stop_order_events, caps.stop_events());
}

/// Enable the opt-in cashflow [`Ledger`] with initial capacity `capacity`, anchored at
/// the current wallet equity.
pub fn enable_ledger(&mut self, capacity: usize) {
Expand Down Expand Up @@ -1966,8 +2012,8 @@ where

/// Give `stop_order_events` enough spare capacity for the next event.
///
/// `#[derive(Clone)]` does not keep spare `Vec` capacity, so a cloned exchange has to
/// allocate on its first stop event. Every other exchange already has the bound.
/// `Clone` restores the bound, so only a deserialized exchange (serde cannot restore
/// spare `Vec` capacity) has to allocate on its first stop event.
#[cold]
#[inline(never)]
fn restore_stop_order_event_capacity(&mut self) {
Expand Down
76 changes: 76 additions & 0 deletions src/execution_rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//! Both venues implement the same order semantics on different account models. Keeping
//! the rules here as pure functions means a fix cannot land in only one of them.

use getset::CopyGetters;
use num_traits::Zero;

use crate::{
Expand All @@ -17,6 +18,7 @@ use crate::{
Currency,
LimitOrder,
MarginCurrency,
MarketId,
Mon,
NewOrder,
QuoteCurrency,
Expand Down Expand Up @@ -330,6 +332,51 @@ where
trade_range.is_some() && price_type == TriggerPriceType::Last
}

/// Capacity of the per-call event and scratch buffers of both exchanges.
///
/// The bounds depend only on the number of order slots `n`: the `max_num_open_orders`
/// of an [`crate::prelude::Exchange`], or the sum over all markets of a
/// [`crate::prelude::PortfolioExchange`]. Bids and asks each rest up to that many
/// orders, and the pending stops are capped at the same number.
/// `new`, `add_market` and `clone` of both exchanges size their buffers from here, so the
/// bounds cannot drift apart. The push paths use `push_within_capacity`, so a bound which
/// is too small panics instead of allocating.
#[derive(Debug, Clone, Copy, PartialEq, Eq, CopyGetters)]
pub(crate) struct BufferCapacities {
/// Fills and forced cancellations of one call: up to `2n` fills of the resting bids and
/// asks plus as many forced cancellations.
#[getset(get_copy = "pub(crate)")]
order_events: usize,
/// Orders force-cancelled between two drains: each of the at most `2n` resting
/// orders is cancelled at most once.
#[getset(get_copy = "pub(crate)")]
forced_cancels: usize,
/// Stops elected by one evaluation, which covers a single market's pending stops.
#[getset(get_copy = "pub(crate)")]
elected_stops: usize,
/// One event per pending stop per call; a portfolio liquidation drains every market.
#[getset(get_copy = "pub(crate)")]
stop_events: usize,
}

impl BufferCapacities {
/// The capacities for `order_slots` slots, see the field docs for each bound.
#[must_use]
pub(crate) fn for_order_slots(order_slots: usize) -> Self {
// Both callers sum `NonZeroU16` limits over at most `MarketId::COUNT` markets.
assert!(order_slots <= MarketId::COUNT * usize::from(u16::MAX));
let caps = Self {
order_events: order_slots * 4,
forced_cancels: order_slots * 2,
elected_stops: order_slots,
stop_events: order_slots,
};
assert!(caps.order_events >= caps.forced_cancels);
assert!(caps.forced_cancels >= caps.elected_stops);
caps
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -339,6 +386,35 @@ mod tests {
PriceFilter,
};

#[test]
fn buffer_capacities_scale_with_order_slots() {
let caps = BufferCapacities::for_order_slots(10);
assert_eq!(caps.order_events(), 40);
assert_eq!(caps.forced_cancels(), 20);
assert_eq!(caps.elected_stops(), 10);
assert_eq!(caps.stop_events(), 10);

// A portfolio without markets has no order slots and must not allocate.
let empty = BufferCapacities::for_order_slots(0);
assert_eq!(empty.order_events(), 0);
assert_eq!(empty.forced_cancels(), 0);
assert_eq!(empty.elected_stops(), 0);
assert_eq!(empty.stop_events(), 0);

// The largest valid input: every market id with the largest order cap.
let max_slots = MarketId::COUNT * usize::from(u16::MAX);
assert_eq!(
BufferCapacities::for_order_slots(max_slots).order_events(),
max_slots * 4
);
}

#[test]
#[should_panic]
fn buffer_capacities_reject_more_slots_than_any_config_allows() {
let _ = BufferCapacities::for_order_slots(MarketId::COUNT * usize::from(u16::MAX) + 1);
}

fn quoted_market(bid: i64, ask: i64) -> MarketState<i64, 5> {
let mut ms = MarketState::<i64, 5>::default();
ms.update_state::<_, BaseCurrency<i64, 5>>(
Expand Down
91 changes: 69 additions & 22 deletions src/portfolio/portfolio_exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ use crate::{
Position,
},
contract_specification::ContractSpecification,
execution_rules::fill_flows,
execution_rules::{
BufferCapacities,
fill_flows,
},
ledger::{
Ledger,
LedgerEntryKind,
Expand Down Expand Up @@ -86,6 +89,7 @@ use crate::{
TimestampNs,
UserOrderId,
},
utils::reserve_to_capacity,
};

/// Internal per-market slot stored contiguously in [`PortfolioExchange::markets`].
Expand Down Expand Up @@ -246,7 +250,7 @@ where
/// All registered markets share a single [`Balances`] wallet. Profits in winning
/// positions offset losses in losing positions under cross-margin, and forced
/// cancellations / liquidations reconcile across the entire portfolio.
#[derive(Debug, Clone, Getters)]
#[derive(Debug, Getters)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde",
Expand Down Expand Up @@ -308,6 +312,40 @@ where
ledger: Option<Ledger<I, D, BaseOrQuote::PairedCurrency>>,
}

impl<I, const D: u8, BaseOrQuote, UserOrderIdT> Clone
for PortfolioExchange<I, D, BaseOrQuote, UserOrderIdT>
where
I: Mon<D>,
BaseOrQuote: Currency<I, D>,
BaseOrQuote::PairedCurrency: MarginCurrency<I, D>,
UserOrderIdT: UserOrderId,
{
/// Clone the portfolio with the pre-allocated buffers of a freshly constructed one.
///
/// `Vec::clone` keeps only the length, so a derived clone left the event and scratch
/// buffers without spare capacity and the first fill, elected stop or forced cancel
/// panicked in `push_within_capacity`. `Clone` is cold, so restoring the bounds here
/// keeps every push path free of capacity checks. The per-market `ActiveLimitOrders`
/// and `PendingStops` retain their own capacity in their `Clone`.
fn clone(&self) -> Self {
let mut cloned = Self {
balances: self.balances.clone(),
markets: self.markets.clone(),
ticker_index: self.ticker_index.clone(),
next_order_id: self.next_order_id,
order_events: self.order_events.clone(),
stop_events: self.stop_events.clone(),
max_pending_stops: self.max_pending_stops,
elected_stops_scratch: self.elected_stops_scratch.clone(),
forced_cancel_scratch: self.forced_cancel_scratch.clone(),
liquidated_during_fills: self.liquidated_during_fills,
ledger: self.ledger.clone(),
};
cloned.reserve_preallocated_capacities();
cloned
}
}

impl<I, const D: u8, BaseOrQuote, UserOrderIdT> PortfolioExchange<I, D, BaseOrQuote, UserOrderIdT>
where
I: Mon<D>,
Expand Down Expand Up @@ -349,24 +387,38 @@ where
.expect(EXPECT_CAPACITY);
}

let scratch_cap = (total_order_cap * 2).max(16);
// `PendingStops` holds up to `max_num_open_orders` stops per market.
let max_pending_stops = total_order_cap;
let caps = BufferCapacities::for_order_slots(total_order_cap);
Self {
balances,
markets,
ticker_index,
next_order_id: OrderId::default(),
order_events: Vec::with_capacity(scratch_cap * 2),
stop_events: Vec::with_capacity(max_pending_stops),
max_pending_stops,
elected_stops_scratch: Vec::with_capacity(scratch_cap),
forced_cancel_scratch: Vec::with_capacity(scratch_cap),
order_events: Vec::with_capacity(caps.order_events()),
stop_events: Vec::with_capacity(caps.stop_events()),
max_pending_stops: total_order_cap,
elected_stops_scratch: Vec::with_capacity(caps.elected_stops()),
forced_cancel_scratch: Vec::with_capacity(caps.forced_cancels()),
liquidated_during_fills: false,
ledger: None,
}
}

/// Give the per-call buffers the capacity [`BufferCapacities`] prescribes for the
/// current set of markets.
///
/// [`Self::new`] allocates them up front, [`Self::add_market`] grows them to the new
/// total and [`PortfolioExchange::clone`] restores them after `Vec::clone` dropped
/// the spare capacity.
fn reserve_preallocated_capacities(&mut self) {
// The summed pending-stop capacity is the summed order capacity of all markets.
let caps = BufferCapacities::for_order_slots(self.max_pending_stops);
assert_eq!(caps.stop_events(), self.max_pending_stops);
reserve_to_capacity(&mut self.order_events, caps.order_events());
reserve_to_capacity(&mut self.stop_events, caps.stop_events());
reserve_to_capacity(&mut self.elected_stops_scratch, caps.elected_stops());
reserve_to_capacity(&mut self.forced_cancel_scratch, caps.forced_cancels());
}

/// Enable the opt-in portfolio cashflow [`Ledger`] anchored at current wallet equity.
pub fn enable_ledger(&mut self, capacity: usize) {
self.ledger = Some(Ledger::with_capacity(self.balances.equity(), capacity));
Expand Down Expand Up @@ -426,17 +478,12 @@ where
}
self.ticker_index.insert(ticker.clone(), market_id);
}
let add_cap = usize::from(market_cfg.max_num_open_orders().get()) * 2;
self.forced_cancel_scratch.reserve(add_cap);
self.order_events.reserve(add_cap * 2);
// `max_pending_stops` is the summed order capacity of all markets, see
// `BufferCapacities`. Grow every buffer to the new total: a relative
// `Vec::reserve` only guarantees `len + additional`, and the buffers are empty
// between calls, so it would not grow them at all.
self.max_pending_stops += usize::from(market_cfg.max_num_open_orders().get());
// `reserve` is relative to `len`, so size against the total stop capacity instead.
self.stop_events.reserve(
self.max_pending_stops
.saturating_sub(self.stop_events.len()),
);
assert!(self.stop_events.capacity() >= self.max_pending_stops);
self.elected_stops_scratch.reserve(add_cap);
self.reserve_preallocated_capacities();
#[allow(
clippy::disallowed_methods,
reason = "add_market is a cold-path dynamic market registration"
Expand Down Expand Up @@ -2155,8 +2202,8 @@ where
/// Clear `stop_events` at the start of a public call which can emit stop events.
///
/// Also restores the capacity bound (one event per possible pending stop of every
/// market), because `#[derive(Clone)]` does not keep spare `Vec` capacity.
/// Allocation-free except on the first call after a clone.
/// market) if it is missing. `Clone` and `add_market` keep it, so only a deserialized
/// portfolio (serde cannot restore spare `Vec` capacity) takes that branch.
#[inline]
fn reset_stop_events(&mut self) {
self.stop_events.clear();
Expand Down
Loading
Loading