dyn4mik3 / OrderBook

Matching Engine for Limit Order Book
Other
361 stars 116 forks source link

Replace bintrees with sortedcontainers #11

Closed grantjenks closed 5 years ago

grantjenks commented 6 years ago

Replace bintrees with sortedcontainers.

nengine commented 5 years ago

Hello, Would it also make sense to replace OrderList class with SortedList instead? Since it is just a collection of orders, not so sure advantage of handling "doubly linked list of Orders" manually, as it would be handled by SortedList already!

    # ordertree.py
    def create_price(self, price):
        self.depth += 1 # Add a price depth level to the tree
        new_list = OrderList()
        self.price_tree.insert(price, new_list) # Insert a new price into the tree
        self.price_map[price] = new_list # Can i just get this by using self.price_tree.get_value(price)? Maybe this is faster though.
BeOleg commented 5 years ago

Hi! I would like to learn what is the advantage of this diff? more speed?

nengine commented 5 years ago

SortedKeyList already handles sorting whenever items are added, removed and it does seem to be optimized for this kind of scenarios, so just my thought. Nothing wrong with rolling your own double linked list to do so. See example below.

orderlist.py

class OrderList(SortedKeyList):
    def __init__(self, iterable=None, key=None):
        super().__init__(iterable=iterable, key=key)

    def __str__(self):
        from six.moves import cStringIO as StringIO
        temp_file = StringIO()
        for order in self:
            temp_file.write("%s\n" % str(order))
        return temp_file.getvalue()

ordertree.py

    def create_price(self, price):
        self.depth += 1 # Add a price depth level to the tree        
        self.price_map[price] = OrderList(key = lambda order: (order.timestamp, order.order_id))