in business-model/src/main/java/com/google/cloud/orderbook/OrderBookBuilder.java [92:141]
public MarketDepth getCurrentMarketDepth(int depth, boolean withTrade) {
// Create market depth
MarketDepth.Builder b = MarketDepth.newBuilder();
// Fill in the depth on the bids and offers
if (depth > 0) {
int bids = 0;
for (Map.Entry<Long, Long> entry : prices.headMap(0L).entrySet()) {
b.addBids(MarketDepth.PriceQuantity.newBuilder()
.setPrice(-1 * entry.getKey())
.setQuantity(entry.getValue())
.build());
bids++;
if (bids == depth) {
break;
}
}
int asks = 0;
for (Map.Entry<Long, Long> entry : prices.tailMap(0L).entrySet()) {
b.addOffers(MarketDepth.PriceQuantity.newBuilder()
.setPrice(entry.getKey())
.setQuantity(entry.getValue())
.build());
asks ++;
if (asks == depth) {
break;
}
}
}
// Add in the last traded price (if any)
// NOTE -- if produceResult() isn't called on every update,
// then you will miss trades!
if (withTrade &&
lastOrderBookEvent.getType().equals(OrderBookEvent.Type.EXECUTED)) {
b.setLastTrade(MarketDepth.PriceQuantity.newBuilder()
.setQuantity(lastOrderBookEvent.getQuantityFilled())
.setPrice(lastOrderBookEvent.getPrice()));
}
// Add in the metadata
b.setTimestampMS(lastOrderBookEvent.getTimestampMS())
.setContractId(lastOrderBookEvent.getContractId())
.setSeqId(lastOrderBookEvent.getSeqId())
.setContractSeqId(lastOrderBookEvent.getContractSeqId());
return b.build();
}