How to create Order Matcher in Go?

Kailash Yogeshwar
5 min readSep 3, 2021

Before jumping to implementation let's first see what is an order matcher why is it so crucial in financial apps. We will refer to the matching engine as OME.

Order Matcher

ordermatcher_engine

Order Matcher is a program that uses an order book to match the buy order (bid) with the sell orders(ask) one or more when the units are matched or match sell order with one or more buy orders to make trades.

Matching orders is the process by which a securities exchange pairs one or more unsolicited buy orders to one or more sell orders to make trades.

Components of OME

  • Order
  • Order Book
  • Trade

Order

Order is a transaction that specifies to buy/sell the security at a market price or limit price. eg: BUY 1000 stocks of MRF @ 80000 INR.

Order Book

Order Book is a ledger that holds the orders often referred to as a bid/ask currently active in the system. Traders usually look into the book to specify the price to buy/sell security.

binance_orderbook

Trade

Trade is a transaction when the orders(bid/ask) are matched with counter orders on the opposite side (bid/ask) that specifies the number of quantities that have been settled for an order.

Working of OME

  1. A user places a buy/sell order for a security eg: BUY 1 BTC at Market Price.
  2. Order is submitted to OME.
  3. Based on the order side i.e Buy/Sell it is saved in a respective queue. If it is a buy it is placed in the bids queue else asks queue.
  4. On every new order OME checks if any orders can be settled, if such orders are found they are settled and partially settled orders are resubmitted to OME.
  5. Bids are stored in descending order so a bid with the highest price is at the top of a bid queue. Similarly, an asks are stored in ascending order with the least price is at the top of the ask queue.
  6. OME continuous to run until there are unsettled orders. Hence it is also called the heart of the exchange.

Types of Orders

  • Market Order
  • Limit Order
  • Stop Order or Stop Loss Order
  • Stop Limit Order
  • Trailing Stop Order

We will just discuss market order and limit order.

Market Order

An order to buy/sell a security at the best market price that is available in the exchange.

Limit Order

An order to buy/sell a security only when the price is less than or equal to the limit price.

Types of Trades

  • fully_settled
  • partially_settled

Trades can be fully settled or partially_settled based on the available liquidity in an exchange.

As long as there is enough liquidity in a exchange orders will be fully_settled.

Partially settled orders are trades that are settled multiple times in chunks.

eg: If Bob has placed an order to 1000 Shares of APPLE but there are only 2 asks orders with a total quantity of 500 so Bob's order will be partially filled with two fills from each ask order.

Matching Algorithm

  • FIFO
  • Pro-Rata

FIFO

In this algorithm, OME will execute the orders in the order of creation. So order placed earlier will be executed than newly added orders.

Pro-Rata

Here OME gives priority to the order with the highest bid price. Orders with the same price are filled with 75% of their quantity.

Implementation

We will take order requests from a Kafka topic (orders) and publish them to a trades topic when there is a settlement.

OME components

  • Order
  • OrderBook
  • Engine (Heart of OME)
  • Side
  • Trade

Order

OrderBook

Engine

Side

Trade

Main

Walkthrough

Order Type

Order type will be used to refer to an order submitted by a user. An order has below properties

  • ID: Unique id create by your API
  • Quantity: Unit of security to buy/sell.
  • Price: Price at which to execute the order eg: BUY 1 APPLE stock when the price reaches $150.
  • Side: Refers to Side Datatype i.e buy/sell
  • Timestamp: Unix epoch

OrderBook Type

OrderBook has two properties Asks and Bids holding buy/sell orders in a respective queue. NOTE: We are not sorting orders in queues which should be done when adding order.

Side Type

Have two properties Sell -> iota i.e(0) and Buy will have a value of 1

Trade Type

Trade data type have below properties

  • MakerOrderId: Order Id making this order. All limit orders are maker orders.
  • TakerOrderId: Order Id taking this order.
  • Quantity: Number of units that have been settled.
  • Price: Settlement price for a trade.
  • Timestamp: Unix epoch.

Step 1: Place an order

An external system i.e your API will publish a message to orders topic

{
"id": "OB1001",
"side": "buy",
"quantity": 10,
"price": 150,
"symbol": "APPLE", // have skipped for our demo
"timestamp": 1234567890
}

Step 2: Engine Processes an order

The engine will listen to the topic and add it to the order book bids queue if it is a buy order else asks queue.

Processing LIMIT Orders

On every order, the engine will match the existing orders to their counterpart based on the below conditions

For Buy Order

  • Process a buy order only when the limit price is less than equal to the current sell price of a security. eg: Current APPLE sell price is 153 and limit price is 150, it will only execute when sell price gets below or equal to 150.
  • We check the price of every sell order if it is greater than we break else continue to match the order quantities and create trade whenever there is a settlement.
  • We publish each trade on trades topic on Kafka and the remaining order is pushed back to a queue.

For Sell Order

  • We process only when the limit price is greater than the current sell price.
  • We check the price of every buy order if it is less than the limit price we break else continue to match the order quantities and create trade whenever there is a settlement.
  • We publish each trade on trades topic and the remaining order is pushed back to a queue.

Improvements that can be added

  • A more efficient matching algorithm.
  • Ability to cancel an order.
  • Back up the order book in persistent storage.
  • Monitoring

Conclusion

This blog is just for educational purposes and should not be used for commercial exchange as there are lots of factors that need to be considered when creating OME.

--

--