techlinks.in
Low Level Design (LLD) Coding

Low Level Design (LLD) Coding

Design a Limit Order Book - Machine Coding Interview

techlinks.in's photo
techlinks.in
·May 1, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

image.png

Limit Order Book

A limit order book is used in stock exchanges to match a buy order with a sell order based on price and time priority

In Stock trading, exchanges like NYSE (New York Stock Exchange) maintains an order book for every security or stock which is traded on their exchange e.g. GOOG, which is a symbol of Google's stock. There are mainly two kinds of orders customers can send, a buy order, and a sell order. When we use Limit Price, which means buy order with a limit price of $50 can be executed if it found a sell order of $50 or an order of lower price says $49, but it can not be executed with a sell order of price $51. Similarly, a sell order can execute for a price, which is either equal to or higher than the limit price. In general, a LIMIT order executes if it found a specified price or better price(lower in the case of a buy, and higher in the case of sell).

Orders are executed on a first come first serve basis, so exchange also maintains a time priority. Now, let's see the flow, an order comes to exchange, exchange looks order book for that symbol, if it found a match it executes order otherwise, it adds that order at the end of a price queue, which represents time priority, head of the queue represents the order with highest time priority i.e. the order which comes before all the order below it.

limit order book aggresive ordre data structure.jpeg

Now our goal is to perform the above operation as quickly as possible. If you look at it closely, it involves finding the opposite order of matching the price, which is equal to or less/greater than the specified price, removing the order from the order book if it matched or canceled, adding order into the order book at an appropriate place if not matched.

Rough Solution (LLD-Machine Coding)

Final Code

class MathcingEngine {

    private Map books;

}

class OrderBook {
    private BinaryTree < Order > orders;

    public execute(Order ord) {
        //find matching order
        //if match found then create trade
        //else add this order into tree
    }
}

Did you find this article valuable?

Support techlinks.in by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this