java – Problem of logical sequencing of the correspondences of order

I have developed a stock exchange where orders are matched in real time with as little latency as possible. The command matching service logic is working properly. However, there is a minute error in the operation.

The sequence is wrong. The explanation below is the example of the order book.

Purchase side:

Price = 3 Qty = 1
Price = 2 Qty = 1
Price = 1 Qty = 1

Now a user comes with a sell order of Qty = 3 at price = 1. In this case, all purchase orders will be executed, but in a sequence of:

First, it will execute the pending order with a purchase price of 3, then 2, then 1.

My correspondence service runs logic, but in the reverse order. Below the code snippet, can anyone help?

if (matchOrderRequest.getOrderType () == OrderType.BUY)
optionalMatchOrder = orderRepository.findFirstByMarketAndOrderTypeAndPriceLessThanEqualOrderByPriceAscTimestampAsc (request.getMarket (), OrderType.SELL, request.getPrice ());


optionalMatchOrder = orderRepository.findFirstByMarketAndOrderTypeAndPriceGreaterThanEqualOrderByPriceDescTimestampAsc (request.getMarket (), OrderType.BUY, request.getPrice ());

There is a lot of logic after that, but it does not make sense to post everything, but if someone needs to know more, I can post it.