I'm looking for code that constructs orderbook from orders
For example if orders are
side | price | quantity
buy 100 1
buy 101 10
buy 100 1000
buy 100 10000
then agregated orderbook should be:
side | price | quantity
buy 100 11001
buy 101 10
During program lifetime orders are added, modified or deleted. On each order update I need to update OrderBook quickly.
I'm sure this is very common task, so there should be a lot of implementations in Internet already.
Thank you for any references, I'm looking for c# implementation, but I can rewrite it from another language if needed.
upd Actually I should rephrase my question. Initially orderbook is empty. Then I receive events: add order, change order quantity or cancel order. I should recalculate orderBook from this messages. But now it becomes clear for me how simple it should be. When order is added I just add quantity at this price level. When order quantity is changed i just need to add "change" and when order is canceled i just need to remove corresponding quantity from corresponding price level. The only question is where should I store "last order quantity" Totally there are a lot of orders (dozens of millions), but there are not a lot of active orders (not more than 100 000) and for each active order I need to obtain "last quantity" by orderId... Of course I can use dictionary, but that would be too slow probably. I want something faster. But I can not use 50 000 000 items array.
Using a query you can do
where :your_price and :your_side are values of modified order.
Better if you can clear all table and fill it from beginning:
In my first example I assumed that in your order only quantity can change; but if other values can change it cannot work.
Second example is expensive, so use it only if your order don't change often.
Finally: if your orders vary often and every value can change you could:
You need to group by the
price
andside
and then select the sum ofquantity
for each group. Since you haven't specified any medium (database, objects in memory, etc.) we can't really give you a specific implementation.Edit: apparently these are object in memory, in which case LINQ is your friend:
Here is the code tested in LINQPad
The result in LINQPad is
Any solution will involve either a tree, or a hashtable. So you're probably better off using the standard dictionary implementation of your language.
Now, don't guess anything about performance, especially before having implemented something that works. Then profile, and if the particular dictionary implementation you're using is proven to impact performance, then ask a specific question with actual code we will be glad to try and improve.