Skip to content

Commit

Permalink
Refresh the code
Browse files Browse the repository at this point in the history
  • Loading branch information
qoqosz committed Aug 12, 2024
1 parent 2273404 commit 5286de2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 59 deletions.
64 changes: 23 additions & 41 deletions src/book.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl Client {
CLIENT_ID.with(|thread_id| {
let id = thread_id.get();
thread_id.set(id + 1);
Client { id: id }
Self { id }
})
}
}
Expand All @@ -52,7 +52,7 @@ impl Order {
ORDER_ID.with(|thread_id| {
let id = thread_id.get();
thread_id.set(id + 1);
Order {
Self {
id,
side,
price,
Expand Down Expand Up @@ -84,6 +84,7 @@ pub enum OrderBookResult {
Canceled, // order canceled
}

#[derive(Default)]
pub struct OrderBook {
bids: Ladder,
asks: Ladder,
Expand All @@ -92,18 +93,13 @@ pub struct OrderBook {

impl OrderBook {
pub fn new() -> OrderBook {
OrderBook {
bids: Ladder::new(),
asks: Ladder::new(),
lookup: HashMap::new(),
}
Self::default()
}

pub fn insert(&mut self, order: Order) -> OrderBookResult {
match self.validate_order(&order) {
Err(e) => return OrderBookResult::Error(e),
_ => {}
};
if let Err(e) = self.validate_order(&order) {
return OrderBookResult::Error(e);
}

if self.is_passive(&order) {
OrderBookResult::OrderId(self.place_passive(order))
Expand All @@ -112,10 +108,10 @@ impl OrderBook {
let trades = self.match_order(&mut order);

match order.size {
0 => OrderBookResult::Trades(trades.unwrap()),
0 => OrderBookResult::Trades(trades.unwrap_or_default()),
_ => {
let order_id = self.place_passive(*order);
OrderBookResult::OrderIdTrades(order_id, trades.unwrap())
OrderBookResult::OrderIdTrades(order_id, trades.unwrap_or_default())
}
}
}
Expand Down Expand Up @@ -146,14 +142,13 @@ impl OrderBook {

fn place_passive(&mut self, order: Order) -> u64 {
let order_id = order.id;
self.lookup
.insert(order_id, (order.side.clone(), order.price));
self.lookup.insert(order_id, (order.side, order.price));
let ladder = self.get_ladder_mut(&order.side);
let price = OrderedFloat(order.price);

match ladder.get_mut(&price) {
Some(level) => {
(*level).push_back(order);
level.push_back(order);
}
_ => {
ladder.insert(price, VecDeque::from(vec![order]));
Expand Down Expand Up @@ -204,17 +199,16 @@ impl OrderBook {
ladder.remove(level_price);
}

match !trades.is_empty() {
true => Some(trades),
false => None,
match trades.is_empty() {
false => Some(trades),
true => None,
}
}

fn get_size(&self, side: Side, price: f64) -> u64 {
match self.get_ladder(&side).get(&OrderedFloat(price)) {
Some(level) => get_level_size(level),
_ => 0,
}
self.get_ladder(&side)
.get(&OrderedFloat(price))
.map_or(0, get_level_size)
}

fn get_ladder(&self, side: &Side) -> &Ladder {
Expand All @@ -233,32 +227,20 @@ impl OrderBook {

/// Best bid price
pub fn best_bid(&self) -> Option<f64> {
match self.bids.keys().rev().next() {
Some(bid) => Some((*bid).into()),
None => None,
}
self.bids.keys().rev().next().map(|bid| (*bid).into())
}

/// Volume of all orders at best bid price
pub fn best_bid_size(&self) -> Option<u64> {
match self.bids.values().rev().next() {
Some(level) => Some(get_level_size(level)),
None => None,
}
self.bids.values().rev().next().map(get_level_size)
}

pub fn best_ask(&self) -> Option<f64> {
match self.asks.keys().next() {
Some(ask) => Some((*ask).into()),
None => None,
}
self.asks.keys().next().map(|ask| (*ask).into())
}

pub fn best_ask_size(&self) -> Option<u64> {
match self.asks.values().next() {
Some(level) => Some(get_level_size(level)),
None => None,
}
self.asks.values().next().map(get_level_size)
}

fn is_passive(&self, order: &Order) -> bool {
Expand Down Expand Up @@ -317,7 +299,7 @@ impl Trade {
TRADE_ID.with(|thread_id| {
let id = thread_id.get();
thread_id.set(id + 1);
Trade { id, price, size }
Self { id, price, size }
})
}
}
Expand All @@ -333,7 +315,7 @@ impl fmt::Display for Trade {
}

fn get_level_size(level: &LadderLevel) -> u64 {
level.into_iter().map(|order| order.size).sum()
level.iter().map(|order| order.size).sum()
}

/// check if
Expand Down
28 changes: 10 additions & 18 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ fn main() {

match ob.insert(order) {
OrderBookResult::Trades(trades) => {
for trade in trades {
println!("{}\n", trade);
}
trades.iter().for_each(|trade| println!("{}", trade));
}
_ => println!("Sth went wrong"),
};
Expand All @@ -42,19 +40,15 @@ fn main() {
order = Order::new(Side::Bid, 0.8, 10, &client1);
println!("Placing order: <{}>", order);

let order_id = match ob.insert(order) {
OrderBookResult::OrderId(id) => id,
_ => 0,
};

println!("\nNew order book\n==============\n{}", ob);
println!("Canceling order: <{}>", order_id);

match ob.cancel(order_id) {
OrderBookResult::Canceled => println!("Order canceled"),
_ => println!("Order could not be canceled"),
};
if let OrderBookResult::OrderId(order_id) = ob.insert(order) {
println!("\nNew order book\n==============\n{}", ob);
println!("Canceling order: <{}>", order_id);

match ob.cancel(order_id) {
OrderBookResult::Canceled => println!("Order canceled"),
_ => println!("Order could not be canceled"),
};
}
println!(
"Order book back to previous state\n=================================\n{}",
ob
Expand All @@ -66,9 +60,7 @@ fn main() {

match ob.insert(order) {
OrderBookResult::OrderIdTrades(order_id, trades) => {
for trade in trades {
println!("{}", trade);
}
trades.iter().for_each(|trade| println!("{}", trade));
println!("Order placed: <{}>", order_id);
}
_ => println!("Sth went wrong"),
Expand Down

0 comments on commit 5286de2

Please sign in to comment.