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
51 changes: 49 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions apex-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ mimalloc = { version = "0.1.46" }
crossbeam = "0.8"
crossbeam-skiplist = "0.1.3"
flurry = "0.5.2"
num-bigint = "0.4.6"
crypto-bigint = { version = "0.6.1", features = [] }

[dev-dependencies]
gnuplot = "0.0.46"
Expand Down
18 changes: 4 additions & 14 deletions apex-core/benches/common.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,21 @@
use apex_core::prelude::*;
use crossbeam::epoch;

/// Quickly generate a simple limit order for testing
pub fn make_limit_order(id: u64, side: Side, price: Price, qty: Quantity, ts: u64) -> Order {
pub fn make_limit_order(id: u64, side: Side, price: u64, qty: u64, ts: u64) -> Order {
let mut value = Order::default();
value.id = id;
value.user_id = 1;
value.side = side;
value.price = price;
*value.quantity.get_mut() = qty;
value.price = Price::from(price);
*value.quantity.get_mut() = Quantity::from(qty);
value.created_at = ts;
value.updated_at = ts;
value
}

/// Quickly generate a market order for testing
pub fn make_market_order(id: u64, side: Side, qty: Quantity, ts: u64) -> Order {
pub fn make_market_order(id: u64, side: Side, qty: u64, ts: u64) -> Order {
let mut value = make_limit_order(id, side, 0, qty, ts);
value.order_type = OrderType::Market;
value
}

/// Get the current state of a side of the book
pub fn get_book_state(book: &dyn OrderBookWalker, side: Side) -> Vec<(OrderID, Quantity)> {
let guard = &epoch::pin();
book.get_book(side)
.iter(guard)
.map(|entry| (entry.value().id, entry.value().quantity()))
.collect()
}
13 changes: 7 additions & 6 deletions apex-core/src/engine/engine.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::prelude::*;
use crypto_bigint::Zero;
use std::sync::Arc;
use std::time::Instant;

Expand Down Expand Up @@ -72,10 +73,10 @@ impl DefaultMatchingEngine {
return WalkingResult::next();
}

remaining_qty = remaining_qty.saturating_sub(maker.quantity());
remaining_qty = remaining_qty.saturating_sub(&maker.quantity());
order_id_list.push(maker.id);

if remaining_qty == 0 {
if remaining_qty.is_zero().into() {
WalkingResult::exit()
} else {
WalkingResult::next()
Expand All @@ -85,7 +86,7 @@ impl DefaultMatchingEngine {
self.order_book
.walking_book_maker(Side::Sell, slippage_price, &mut walking);

if remaining_qty == 0 {
if remaining_qty.is_zero().into() {
return Some(order_id_list);
}

Expand Down Expand Up @@ -117,7 +118,7 @@ impl DefaultMatchingEngine {
let mut process = |maker: &Order| {
let removed =
DefaultMatchingEngine::process_order_pair(taker, maker, &mut updated, &mut matched);
WalkingResult::new(removed, taker.quantity() == 0)
WalkingResult::new(removed, taker.quantity().is_zero().into())
};
self.order_book
.walking_by_order_id_list(order_id_list_opt.unwrap().as_slice(), &mut process);
Expand Down Expand Up @@ -158,7 +159,7 @@ impl DefaultMatchingEngine {
}
let removed =
DefaultMatchingEngine::process_order_pair(taker, maker, &mut updated, &mut matched);
WalkingResult::new(removed, taker.quantity() == 0)
WalkingResult::new(removed, taker.quantity().is_zero().into())
};
self.order_book
.walking_book_maker(opposite_side, slippage_price, &mut process);
Expand Down Expand Up @@ -193,7 +194,7 @@ impl DefaultMatchingEngine {
}
let removed =
DefaultMatchingEngine::process_order_pair(taker, maker, &mut updated, &mut matched);
WalkingResult::new(removed, taker.quantity() == 0)
WalkingResult::new(removed, taker.quantity().is_zero().into())
};
self.order_book
.walking_book_maker(opposite_side, Some(taker.price), &mut process);
Expand Down
40 changes: 24 additions & 16 deletions apex-core/src/engine/types.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crypto_bigint::{Limb, NonZero, Reciprocal, U256, U512, Zero};
use mimalloc::MiMalloc;
use std::cell::UnsafeCell;
use std::ops::Mul;
use std::sync::atomic::{AtomicU8, Ordering};

/// Global allocator
Expand All @@ -11,12 +13,12 @@ static GLOBAL: MiMalloc = MiMalloc;
pub type OrderID = u64;

/// Price is the type used for prices in the order.
/// This is a 64-bit unsigned integer.
pub type Price = u64;
/// This is a 256-bit unsigned integer.
pub type Price = U256;

/// Quantity is the type used for quantities in the order.
/// This is a 64-bit unsigned integer.
pub type Quantity = u64;
/// This is a 256-bit unsigned integer.
pub type Quantity = U256;

/// Priority is that the order book uses to determine the order priority.
pub type Priority = u64;
Expand Down Expand Up @@ -166,7 +168,10 @@ pub struct SlippageTolerance(pub u32);

/// Maximum slippage tolerance allowed.
/// This is set to 50% (5000 bps).
pub const MAX_SLIPPAGE_TOLERANCE: SlippageTolerance = SlippageTolerance(5000);
pub const MAX_ALLOWED_SLIPPAGE_TOLERANCE: SlippageTolerance = SlippageTolerance(5000);

/// a constant used for calculating slippage tolerance.
const RECIPROCAL_10000: Reciprocal = Reciprocal::new(NonZero::<Limb>::new_unwrap(Limb(10_000u64)));

/// BookKey is a composite key for identifying an order's position in the book.
/// It combines the order's price, priority (timestamp-based), and side (Buy/Sell).
Expand Down Expand Up @@ -308,10 +313,10 @@ impl Default for Order {
match_strategy: MatchStrategy::default(),
liquidity_directive: LiquidityDirective::default(),
time_in_force: TimeInForce::default(),
price: 0,
price: U256::ZERO,
slippage_tolerance: None,
quantity: UnsafeCell::new(0),
filled_quantity: UnsafeCell::new(0),
quantity: UnsafeCell::new(U256::ZERO),
filled_quantity: UnsafeCell::new(U256::ZERO),
cancel_reason: UnsafeCell::new(None),
reject_reason: UnsafeCell::new(None),
created_at: 0,
Expand Down Expand Up @@ -510,12 +515,15 @@ impl Order {
if self.slippage_tolerance.is_none() {
return None;
}

let slippage = self.slippage_tolerance.unwrap();
let slippage_bps = slippage.0 as f64 / 10000.0;
let slippage_difference = (self.price as f64 * slippage_bps) as u64;
let mut factor = U512::from(slippage.0);
factor = factor.mul(price);
let (quotient, _) = factor.div_rem_limb_with_reciprocal(&RECIPROCAL_10000);
let (lo, _) = quotient.split();
let bound_price = match self.side {
Side::Buy => price + slippage_difference,
Side::Sell => price - slippage_difference,
Side::Buy => price + lo,
Side::Sell => price - lo,
};
Some(bound_price)
}
Expand Down Expand Up @@ -565,7 +573,7 @@ impl Order {
}
// 4. SlippageTolerance could be None or a valid value
if let Some(slippage) = self.slippage_tolerance {
if slippage.0 > MAX_SLIPPAGE_TOLERANCE.0 {
if slippage.0 > MAX_ALLOWED_SLIPPAGE_TOLERANCE.0 {
return Err(OrderValidationError::SlippageExceedsMaximum);
}
}
Expand Down Expand Up @@ -594,19 +602,19 @@ impl Trade {
let mut maker_quantity = maker.quantity();
let mut taker_quantity = taker.quantity();
let traded_quantity = taker_quantity.min(maker_quantity);
if traded_quantity == 0 {
if traded_quantity.is_zero().into() {
return None;
}

maker_quantity = maker.quantity_fill(traded_quantity);
taker_quantity = taker.quantity_fill(traded_quantity);

let maker_status = if maker_quantity == 0 {
let maker_status = if maker_quantity.is_zero().into() {
OrderStatus::Filled
} else {
OrderStatus::PartiallyFilled
};
let taker_status = if taker_quantity == 0 {
let taker_status = if taker_quantity.is_zero().into() {
OrderStatus::Filled
} else {
OrderStatus::PartiallyFilled
Expand Down
8 changes: 4 additions & 4 deletions apex-core/tests/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@ use crossbeam::epoch::default_collector;
use crossbeam_skiplist::SkipList;

/// Quickly generate a simple limit order for testing
pub fn make_limit_order(id: u64, side: Side, price: Price, qty: Quantity, ts: u64) -> Order {
pub fn make_limit_order(id: u64, side: Side, price: u64, qty: u64, ts: u64) -> Order {
let mut value = Order::default();
value.id = id;
value.user_id = 1;
value.side = side;
value.price = price;
*value.quantity.get_mut() = qty;
value.price = Price::from(price);
*value.quantity.get_mut() = Quantity::from(qty);
value.created_at = ts;
value.updated_at = ts;
value
}

/// Quickly generate a market order for testing
pub fn make_market_order(id: u64, side: Side, qty: Quantity, ts: u64) -> Order {
pub fn make_market_order(id: u64, side: Side, qty: u64, ts: u64) -> Order {
let mut value = make_limit_order(id, side, 0, qty, ts);
value.order_type = OrderType::Market;
value
Expand Down
10 changes: 5 additions & 5 deletions apex-core/tests/limit_orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ fn test_limit_order_multiple_partial_fills() {
);
assert_eq!(
remaining_sell[0],
(2, 2),
(2, Quantity::from(2u32)),
"Sell2 should have 2 remaining units"
);
}
Expand Down Expand Up @@ -179,8 +179,8 @@ fn test_limit_order_partial_and_full_match() {
.collect();

assert_eq!(remaining.len(), 2);
assert_eq!(remaining[0], (101, 4));
assert_eq!(remaining[1], (102, 10));
assert_eq!(remaining[0], (101, Quantity::from(4u32)));
assert_eq!(remaining[1], (102, Quantity::from(10u32)));
}

#[test]
Expand Down Expand Up @@ -216,6 +216,6 @@ fn test_limit_order_iter_continues_after_remove() {
.collect();

assert_eq!(remaining.len(), 2);
assert_eq!(remaining[0], (102, 5));
assert_eq!(remaining[1], (103, 10));
assert_eq!(remaining[0], (102, Quantity::from(5u32)));
assert_eq!(remaining[1], (103, Quantity::from(10u32)));
}
5 changes: 3 additions & 2 deletions apex-core/tests/market_orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ fn test_market_order_slippage_exceeded_cancel() {

// Create a market buy order with tight slippage
let mut buy = make_market_order(3, Side::Buy, 10, 1002); // Wants 10 units
buy.slippage_tolerance = Some(SlippageTolerance(10)); // 0.10% slippage allowed
buy.slippage_tolerance = Some(SlippageTolerance(100)); // 1.00% slippage allowed
engine.create_order(&mut buy).unwrap();

engine.match_orders();
Expand All @@ -152,7 +152,8 @@ fn test_market_order_slippage_exceeded_cancel() {
"Remaining sell order should be sell2 (id=2)"
);
assert_eq!(
remaining_sell[0].1, 10,
remaining_sell[0].1,
Quantity::from(10u32),
"Sell2 should have full quantity left"
);
}
Expand Down
Loading
Loading