1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
use std::{cell::RefCell, collections::HashMap, fmt::Display, rc::Rc};
use rust_decimal::Decimal;
use crate::{
bookside::{BookSide, BookSideIter, MaxPricePriority, MinPricePriority},
errors::{self, ProcessLimitOrder, ProcessMarketOrder},
order::{Order, Side, ID},
};
#[derive(Debug)]
pub struct OrderBook {
// every active order is in: order_index AND (buy_side XOR sell_side)
order_index: HashMap<ID, Rc<RefCell<Order>>>,
buy_side: BookSide<MaxPricePriority>,
sell_side: BookSide<MinPricePriority>,
// increments on each new order added to data structures
priority: u64,
}
impl OrderBook {
/// Create new initialized OrderBook
pub fn new() -> Self {
OrderBook {
order_index: HashMap::new(),
buy_side: BookSide::new(),
sell_side: BookSide::new(),
priority: u64::MIN,
}
}
/// Process new limit order
/// ```
/// use rust_ob::{
/// OrderBook,
/// Side,
/// OrderMatch,
/// errors,
/// };
/// use rust_decimal::Decimal;
///
/// let mut ob = OrderBook::new();
///
/// let res1 = ob.process_limit_order(1, Side::Sell, Decimal::from(4), Decimal::from(4)).unwrap();
/// assert_eq!(res1.len(), 0);
///
/// let res2 = ob.process_limit_order(2, Side::Sell, Decimal::from(3), Decimal::from(2)).unwrap();
/// assert_eq!(res2.len(), 0);
///
/// let res3 = ob.process_limit_order(3, Side::Buy, Decimal::from(8), Decimal::from(3)).unwrap();
/// assert_eq!(
/// res3,
/// vec![
/// OrderMatch {
/// order: 2,
/// quantity: Decimal::from(2),
/// cost: Decimal::from(-6)
/// },
/// OrderMatch {
/// order: 1,
/// quantity: Decimal::from(1),
/// cost: Decimal::from(-4)
/// },
/// OrderMatch {
/// order: 3,
/// quantity: Decimal::from(3),
/// cost: Decimal::from(10)
/// }
/// ]
/// );
///
///
/// // all costs sum to zero
/// assert_eq!(res3.iter().map(|val| val.cost).sum::<Decimal>(), Decimal::ZERO);
///
/// // quantity on sell orders == quantity on buy orders
/// // last OrderMatch of Vec (if not empty) is always the order just placed
/// assert_eq!(res3.iter().map(|val| val.quantity).sum::<Decimal>(), res3.last().unwrap().quantity * Decimal::from(2));
///
/// // possible errors
/// assert_eq!(ob.process_limit_order(4, Side::Buy, Decimal::from(10), Decimal::from(0)).unwrap_err(), errors::ProcessLimitOrder::NonPositiveQuantity);
/// assert_eq!(ob.process_limit_order(1, Side::Buy, Decimal::from(10), Decimal::from(25)).unwrap_err(), errors::ProcessLimitOrder::OrderAlreadyExists);
///
///
/// ```
pub fn process_limit_order(
&mut self,
id: ID,
side: Side,
price: Decimal,
mut quantity: Decimal,
) -> Result<Vec<OrderMatch>, errors::ProcessLimitOrder> {
// check to ensure order does not already exist
if self.order_index.contains_key(&id) {
return Err(errors::ProcessLimitOrder::OrderAlreadyExists);
}
// check to ensure positive quantity
if quantity <= Decimal::ZERO {
return Err(errors::ProcessLimitOrder::NonPositiveQuantity);
}
// vars
let mut match_vec = Vec::new();
let mut new_order_match = OrderMatch::new(id);
// main matching loop
while quantity > Decimal::ZERO {
// get highest priority order on opposite side
let shared_highest_priority_order = {
let option_shared_order = match side {
Side::Buy => self.sell_side.get_highest_priority(),
Side::Sell => self.buy_side.get_highest_priority(),
};
match option_shared_order {
Some(val) => val,
None => break,
}
};
let mut highest_priority_order = shared_highest_priority_order.borrow_mut();
// check if orders satisfy each other
let satisfied = match side {
Side::Buy => price >= highest_priority_order.price,
Side::Sell => price <= highest_priority_order.price,
};
if !satisfied {
break;
}
// create Match for highest_priority_order
let mut highest_priority_order_match = OrderMatch::new(highest_priority_order.id);
// find satisfied quantity and update vars
let satisfied_quantity = quantity.min(highest_priority_order.quantity);
quantity = quantity
.checked_sub(satisfied_quantity)
.unwrap_or_else(|| panic!("OrderBook: subtraction overflow"));
highest_priority_order.quantity = highest_priority_order
.quantity
.checked_sub(satisfied_quantity)
.unwrap_or_else(|| panic!("OrderBook: subtraction overflow"));
new_order_match.quantity = new_order_match
.quantity
.checked_add(satisfied_quantity)
.unwrap_or_else(|| panic!("OrderBook: addition overflow"));
highest_priority_order_match.quantity = highest_priority_order_match
.quantity
.checked_add(satisfied_quantity)
.unwrap_or_else(|| panic!("OrderBook: addition overflow"));
// find cost and update vars
let buy_side_cost = highest_priority_order
.price
.checked_mul(satisfied_quantity)
.unwrap_or_else(|| panic!("OrderBook: multiplication overflow"));
match side {
Side::Buy => {
new_order_match.cost = new_order_match
.cost
.checked_add(buy_side_cost)
.unwrap_or_else(|| panic!("OrderBook: addition overflow"));
highest_priority_order_match.cost = -buy_side_cost
}
Side::Sell => {
new_order_match.cost = new_order_match
.cost
.checked_sub(buy_side_cost)
.unwrap_or_else(|| panic!("OrderBook: subtraction overflow"));
highest_priority_order_match.cost = buy_side_cost
}
}
// remove highest_priority_order from orderbook if completely satisfied
if highest_priority_order.quantity == Decimal::ZERO {
self.order_index.remove(&highest_priority_order.id);
match highest_priority_order.side {
Side::Buy => {
drop(highest_priority_order);
self.buy_side.pop_highest_priority();
}
Side::Sell => {
drop(highest_priority_order);
self.sell_side.pop_highest_priority();
}
}
}
// add to result vec
match_vec.push(highest_priority_order_match);
}
// add to result vec if not empty
if !new_order_match.quantity.is_zero() {
match_vec.push(new_order_match);
}
// add order to data structures if any remaining quantity
if !quantity.is_zero() {
let shared_order = Rc::new(RefCell::new(Order {
id,
side,
price,
quantity,
priority: self.get_priority(),
}));
self.order_index.insert(id, shared_order.clone());
match side {
Side::Buy => self.buy_side.add(shared_order),
Side::Sell => self.sell_side.add(shared_order),
}
}
Ok(match_vec)
}
/// Cancels order with id
/// ```
/// use rust_ob::{
/// OrderBook,
/// Side,
/// errors,
/// };
/// use rust_decimal::Decimal;
///
/// let mut ob = OrderBook::new();
/// let _ = ob.process_limit_order(884213, Side::Sell, Decimal::from(5), Decimal::from(5));
///
/// assert_eq!(ob.cancel_order(884213), Ok(()));
///
/// // possible errors
/// assert_eq!(ob.cancel_order(884213), Err(errors::CancelOrder::OrderNotFound));
/// ```
pub fn cancel_order(&mut self, id: ID) -> Result<(), errors::CancelOrder> {
match self.order_index.remove(&id) {
Some(shared_order) => {
let side;
{
let order = shared_order.borrow();
side = order.side;
}
match side {
Side::Buy => self.buy_side.remove(shared_order),
Side::Sell => self.sell_side.remove(shared_order),
}
Ok(())
}
None => Err(errors::CancelOrder::OrderNotFound),
}
}
/// Calculates cost to buy/sell up to quantity.
/// This function does not mutate anything in OrderBook.
/// The return tuple is in format (quantity_fulfilled, cost).
/// ```
/// use rust_ob::{
/// OrderBook,
/// Side,
/// errors,
/// };
/// use rust_decimal::Decimal;
///
/// let mut ob = OrderBook::new();
/// let _ = ob.process_limit_order(1, Side::Buy, Decimal::from(5), Decimal::from(5));
/// let _ = ob.process_limit_order(2, Side::Buy, Decimal::from(3), Decimal::from(3));
///
/// assert_eq!(ob.calculate_market_cost(Side::Sell, Decimal::from(6)).unwrap(), (Decimal::from(6), Decimal::from(-28)));
/// assert_eq!(ob.calculate_market_cost(Side::Sell, Decimal::from(12)).unwrap(), (Decimal::from(8), Decimal::from(-34)));
///
/// // possible errors
/// assert_eq!(ob.calculate_market_cost(Side::Sell, Decimal::from(0)), Err(errors::CalculateMarketCost::NonPositiveQuantity));
/// ```
pub fn calculate_market_cost(
&self,
side: Side,
mut quantity: Decimal,
) -> Result<(Decimal, Decimal), errors::CalculateMarketCost> {
// check to ensure positive quantity
if quantity <= Decimal::ZERO {
return Err(errors::CalculateMarketCost::NonPositiveQuantity);
}
// inits
let mut quantity_fulfilled = Decimal::ZERO;
let mut cost = Decimal::ZERO;
let mut oppisite_side_iter = match side {
Side::Buy => BookSideIter::SellSide(self.sell_side.iter()),
Side::Sell => BookSideIter::BuySide(self.buy_side.iter()),
};
while !quantity.is_zero() {
let shared_order = match oppisite_side_iter {
BookSideIter::BuySide(ref mut iter) => {
iter.next().map(|(_, shared_order)| shared_order)
}
BookSideIter::SellSide(ref mut iter) => {
iter.next().map(|(_, shared_order)| shared_order)
}
};
let order = match shared_order {
Some(val) => val.borrow(),
None => break,
};
let satisfied_quantity = quantity.min(order.quantity);
quantity = quantity
.checked_sub(satisfied_quantity)
.unwrap_or_else(|| panic!("OrderBook: subtraction overflow"));
quantity_fulfilled = quantity_fulfilled
.checked_add(satisfied_quantity)
.unwrap_or_else(|| panic!("OrderBook: addition overflow"));
let buy_side_cost = order
.price
.checked_mul(satisfied_quantity)
.unwrap_or_else(|| panic!("OrderBook: multiplication overflow"));
match side {
Side::Buy => {
cost = cost
.checked_add(buy_side_cost)
.unwrap_or_else(|| panic!("OrderBook: addition overflow"));
}
Side::Sell => {
cost = cost
.checked_sub(buy_side_cost)
.unwrap_or_else(|| panic!("OrderBook: subtraction overflow"));
}
}
}
Ok((quantity_fulfilled, cost))
}
/// Process new market order
/// ```
/// use rust_ob::{
/// OrderBook,
/// Side,
/// OrderMatch,
/// errors,
/// };
/// use rust_decimal::Decimal;
///
/// let mut ob = OrderBook::new();
/// let _ = ob.process_limit_order(1, Side::Sell, Decimal::from(5), Decimal::from(5));
/// let _ = ob.process_limit_order(2, Side::Sell, Decimal::from(3), Decimal::from(3));
///
/// assert_eq!(
/// ob.process_market_order(3, Side::Buy, Decimal::from(6)).unwrap(),
/// vec![
/// OrderMatch {
/// order: 2,
/// quantity: Decimal::from(3),
/// cost: Decimal::from(-9)
/// },
/// OrderMatch {
/// order: 1,
/// quantity: Decimal::from(3),
/// cost: Decimal::from(-15)
/// },
/// OrderMatch {
/// order: 3,
/// quantity: Decimal::from(6),
/// cost: Decimal::from(24)
/// }
/// ]
/// );
///
/// // possible errors
/// assert_eq!(ob.process_market_order(4, Side::Buy, Decimal::from(0)), Err(errors::ProcessMarketOrder::NonPositiveQuantity));
/// assert_eq!(ob.process_market_order(1, Side::Buy, Decimal::from(3)), Err(errors::ProcessMarketOrder::OrderAlreadyExists));
/// ```
pub fn process_market_order(
&mut self,
id: ID,
side: Side,
quantity: Decimal,
) -> Result<Vec<OrderMatch>, ProcessMarketOrder> {
// get min or max price based on side
let price = match side {
Side::Buy => Decimal::MAX,
Side::Sell => Decimal::MIN,
};
let result = self
.process_limit_order(id, side, price, quantity)
.map_err(|e| match e {
ProcessLimitOrder::NonPositiveQuantity => ProcessMarketOrder::NonPositiveQuantity,
ProcessLimitOrder::OrderAlreadyExists => ProcessMarketOrder::OrderAlreadyExists,
});
if let Ok(ref order_match_vec) = result {
if order_match_vec.len() == 0 || order_match_vec.last().unwrap().quantity != quantity {
assert_eq!(self.cancel_order(id), Ok(()));
}
}
result
}
fn get_priority(&mut self) -> u64 {
self.priority += 1;
self.priority
}
}
impl Display for OrderBook {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
const PADDING: usize = 18;
writeln!(
f,
"{:->PADDING$}{:->PADDING$}{:->PADDING$}{:->PADDING$}",
"ID", "SIDE", "PRICE", "QUANTITY"
)?;
let sell_side: Vec<Rc<RefCell<Order>>> = self
.sell_side
.iter()
.map(|(_, shared_order)| shared_order.clone())
.collect();
for shared_order in sell_side
.iter()
.rev()
.chain(self.buy_side.iter().map(|(_, shared_order)| shared_order))
{
let order = shared_order.borrow();
writeln!(
f,
"{:>PADDING$}{:>PADDING$}{:>PADDING$}{:>PADDING$}",
order.id,
order.side.to_string(),
order.price,
order.quantity
)?;
}
write!(f, "")
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct OrderMatch {
pub order: ID,
pub quantity: Decimal,
pub cost: Decimal,
}
impl OrderMatch {
fn new(order: ID) -> Self {
OrderMatch {
order,
quantity: Decimal::ZERO,
cost: Decimal::ZERO,
}
}
}