Stocks go up and down. Do you know what data structure is used to efficiently match buy and sell orders? Stock exchanges use order books. An order book is an electronic list of buy and sell orders, organized by price levels. It has a buy book and a sell book, where each side of the book contains a bunch of price levels, and each price level contains a list of orders (first in first out).
First filter out, invalid requests such as requests placed outside stock exchange working hours, requests from clients without sufficient funds, etc. Next, we can first separate the buy and sell orders into separate heap (or priority queue) data structure, with the highest buying price at the top of the buy queue and the lowest selling price at the top of the sell queue. Then, we can iterate through both queues and match orders based on price until one of the queues is empty.
Match buy and sell stock orders
First filter out, invalid requests such as requests placed outside stock exchange working hours, requests from clients without sufficient funds, etc. Next, we can first separate the buy and sell orders into separate heap (or priority queue) data structure, with the highest buying price at the top of the buy queue and the lowest selling price at the top of the sell queue. Then, we can iterate through both queues and match orders based on price until one of the queues is empty.
What happens for pre market orders?
Some average price is decided there
Low level design of a stock exchange very well explained.