Skip to content

Instantly share code, notes, and snippets.

@miku
Last active September 25, 2024 12:08
Show Gist options
  • Save miku/4b1484b3c3ff98a7f01bf4482960de41 to your computer and use it in GitHub Desktop.
Save miku/4b1484b3c3ff98a7f01bf4482960de41 to your computer and use it in GitHub Desktop.
4-1
/** getSpread returns the difference between the highest bid and the lowest
* offer (ask). It throws an exception, if the orders do not contain both bids
* and asks. */
double OrderBook::getSpread(std::vector<OrderBookEntry>& orders)
{
if (orders.empty()) {
return 0;
}
// https://web.stanford.edu/class/cme241/lecture_slides/Tour-OrderBook.pdf#page=3
double maxBidPrice = -std::numeric_limits<double>::infinity();
double minAskPrice = std::numeric_limits<double>::infinity();
bool hasAsks = false;
bool hasBids = false;
for (OrderBookEntry& e : orders) {
if (e.orderType == OrderBookType::bid) {
hasBids = true;
if (e.price > maxBidPrice) {
maxBidPrice = e.price;
}
}
if (e.orderType == OrderBookType::ask) {
hasAsks = true;
if (e.price < minAskPrice) {
minAskPrice = e.price;
}
}
}
// reject invalid data
if (!hasAsks || !hasBids) {
throw std::invalid_argument("data must contain both asks and bids");
}
return minAskPrice - maxBidPrice;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment