this.performMatching(order.getSymbol());
}
private void performMatching(String symbol) {
logger.debug("Pricing engine triggered for symbol {}", symbol);
MarketPrice marketPrice =
marketDataRepository.findMarketPrice(symbol);
Money preMatchingPrice = marketPrice.getPrice();
OrderBook orderBook = getOrderBook(symbol);
// Iterate through buy orders
for (Order buyOrder : orderBook.getBuyStack()) {
logger.debug("Trying to match buy order:\n{}", buyOrder);
MatchResult matchResult =
new MatchResult(false, NoMatchReason.priceMismatch);
// Iterate through sell orders to match the current buy order
for (Order sellOrder : orderBook.getSellStack()) {
// Skip sell order if it has been filled in a previous iteration
if (!sellOrder.isActive()) {
continue;
}
matchResult = matchOrder(buyOrder, sellOrder, marketPrice);
// Analyze match result and break out of inner loop if appropriate
if (matchResult.isMatch()) {
if (buyOrder.getStatus() == OrderStatus.Filled) {
logger.debug("Buy order filled, stop matching with sell orders");
break;
}
}
else { // no match
if (matchResult.noMatchReason == NoMatchReason.priceMismatch) {
logger.debug("Buy order did not match due to price mismatch, stop matching with sell orders");
break;
}
}
}
// If buy order did not match due to price mismatch, then break.
// (No other buy orders will match.)
if (matchResult.isMatch()==false &&
matchResult.getNoMatchReason()==NoMatchReason.priceMismatch) {
logger.debug("Buy order did not match due to price mismatch, stop matching other buy orders");
break;
}
}
// If market price has changed are a result of this run, publish the new price
if (!marketPrice.getPrice().eq(preMatchingPrice)) {
marketDataEventPublisher.publish(new MarketPriceChanged(marketPrice));
}
}