As suggested here, I'm using Boost multi-index to implement orderbook. So far my code looks like this:
"CommonsNative.h"
contains typedef int64_t myDecimal;
and enum Side { Buy, Sell };
#pragma once
#include "CommonsNative.h"
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
using boost::multi_index_container;
using namespace boost::multi_index;
struct OrderBookItem {
myDecimal price;
int32_t lots;
OrderBookItem(myDecimal price_) :price(price_), lots(0) {
}
};
typedef multi_index_container
<OrderBookItem, indexed_by<
hashed_unique<
BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price)
>,
ordered_unique<
BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price),
std::greater<myDecimal> /* sorted beginning with most frequent */
>
>> OrderBookContainer;
class OrderBook
{
public:
OrderBook(void);
~OrderBook(void);
void Add(Side side_, myDecimal price_, int lots_)
{
if (side_ == Buy) {
// inserts or returns existent
OrderBookContainer::iterator it = buyContainer.insert(price_).first;
// how to add lots i.e. OrderBookItem.lots += lots_?
// auto curLevel = buyContainer.get<name>(price);
// curLevel.lots += Lots;
} else if (side_ == Sell) {
// inserts or returns existent
OrderBookContainer::iterator it = sellContainer.insert(price_).first;
}
}
private:
OrderBookContainer buyContainer;
OrderBookContainer sellContainer;
};
I have the following questions:
For here:
OrderBookContainer::iterator it = buyContainer.insert(price_).first;
If I already have an item with
price = price_
I receive it in \$O(1)\$ (from hashtable). If such a level doesn't exist, then is it added in \$O(log n)\$? If I'm wrong, then what should I write to get an item if it exists (in \$O(1)\$) otherwise add it (in \$O(log n)\$)?Once I have an item, how can I modify
lots
to something like this?OrderBookItem.lots += lots_