Skip to content

Instantly share code, notes, and snippets.

@prystupa
Last active December 10, 2015 01:58
Show Gist options
  • Save prystupa/4363481 to your computer and use it in GitHub Desktop.
Save prystupa/4363481 to your computer and use it in GitHub Desktop.
Order book with implementation that maintain price priority for Buy orders
class OrderBook(side: Side, orderTypes: (Order => OrderType)) {
private var limitBook: List[(Double, List[Order])] = Nil
def add(order: Order) {
orderTypes(order).price match {
case LimitPrice(level) => addLimit(level, order)
}
}
def orders(): List[Order] = limitBook.flatMap({
case (_, orders) => orders
})
private def addLimit(limit: Double, order: Order) {
def insert(list: List[(Double, List[Order])]): List[(Double, List[Order])] = list match {
case Nil => List((limit, List(order)))
case (head@(bookLevel, orders)) :: tail => level.compare(bookLevel) match {
case 0 => (bookLevel, orders :+ order) :: tail
case n if n < 0 => (level, List(order)) :: list
case _ => head :: insert(tail)
}
}
limitBook = insert(limitBook)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment