Match Buy and Sell Orders from an Order Book

Problem Given a list of order-book entries — each with type (BUY/SELL), price, and quantity — implement an order-matching function that returns all matched trades.

Matching rules:

  • A BUY at price P matches the lowest-priced SELL with price ≤ P.
  • A SELL at price P matches the highest-priced BUY with price ≥ P.
  • Partial fills are allowed; unmatched remainder stays resting in the book.

Input / Output

  • Input: ordered list of orders {type, price, quantity}.
  • Output: list of trades {buy_price, sell_price, quantity}.

Constraints

  • Orders are processed in arrival order; leftover quantity rests in the book for later matches.

Example

orders = [
  {type:BUY,  price:102, qty:10},
  {type:SELL, price:100, qty:8},
  {type:SELL, price:101, qty:5},
]
Output: [{buy:102, sell:100, qty:8}, {buy:102, sell:101, qty:2}]
added …
LeaderboardSalaryAccount