List<LimitOrder> buySide = ob.buySide();
List<LimitOrder> sellSide = ob.sellSide();
while (buySide.size() > 0 && sellSide.size() > 0 && buySide.get(0).getLimitPrice() >= sellSide.get(0).getLimitPrice()) {
LimitOrder buyOrder = buySide.get(0);
LimitOrder sellOrder = sellSide.get(0);
double difference = buyOrder.getOpenQuantity() - sellOrder.getOpenQuantity();
double executed = 0.0;
double relevantPrice = sellOrder.getLimitPrice();
// determine the relevant price.
if (buyOrder.getWorkingTimeStamp().compareTo(sellOrder.getWorkingTimeStamp()) < 0)
relevantPrice = buyOrder.getLimitPrice();
if (difference > 0) {
// buy side larger.
executed = buyOrder.getOpenQuantity() + difference;
buyOrder.setOpenQuantity(difference);
sellOrder.setOpenQuantity(0);
} else if (difference < 0) {
executed = sellOrder.getOpenQuantity() + difference;
// sell side larger.
buyOrder.setOpenQuantity(0);
sellOrder.setOpenQuantity(Math.abs(difference));
} else {
// both fully executed.
executed = buyOrder.getOpenQuantity();
sellOrder.setOpenQuantity(0);
buyOrder.setOpenQuantity(0);
}
//
exchange.execution(buyOrder, relevantPrice, executed);
exchange.execution(sellOrder, relevantPrice, executed);
//
if (sellOrder.getOpenQuantity() == 0)
sellSide.remove(0);
if (buyOrder.getOpenQuantity() == 0)
buySide.remove(0);