Last active
December 10, 2015 01:58
-
-
Save prystupa/4363493 to your computer and use it in GitHub Desktop.
Implementation of OrderBook that supports price priority for both Buy and Sell orders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OrderBook(side: Side, orderTypes: (Order => OrderType)) { | |
private var limitBook: List[(Double, List[Order])] = Nil | |
private val priceOrdering = if (side == Sell) Ordering[Double] else Ordering[Double].reverse | |
def add(order: Order) { | |
orderTypes(order).price match { | |
case LimitPrice(limit) => addLimit(limit, 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 => priceOrdering.compare(limit, bookLevel) match { | |
case 0 => (bookLevel, orders :+ order) :: tail | |
case n if n < 0 => (limit, 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