Skip to content

matching_engine

MatchingEngine

Order Book Matching Engine.

Parameters:

Name Type Description Default
seed int | None

Random seed

None

Examples:

>>> from datetime import datetime, timedelta
>>> from pprint import pp
>>> from order_matching.matching_engine import MatchingEngine
>>> from order_matching.order import LimitOrder
>>> from order_matching.enums import Side
>>> from order_matching.orders import Orders
>>> matching_engine = MatchingEngine(seed=123)
>>> timestamp = datetime(2023, 1, 1)
>>> transaction_timestamp = timestamp + timedelta(days=1)
>>> buy_order = LimitOrder(side=Side.BUY, price=1.2, size=2.3, timestamp=timestamp, order_id="a", trader_id="x")
>>> sell_order = LimitOrder(side=Side.SELL, price=0.8, size=1.6, timestamp=timestamp, order_id="b", trader_id="y")
>>> matching_engine.place(orders=Orders([buy_order, sell_order]))
>>> executed_trades = matching_engine.match(timestamp=transaction_timestamp)
>>> pp(executed_trades.trades)
[Trade(side=SELL,
       price=1.2,
       size=1.6,
       incoming_order_id='b',
       book_order_id='a',
       execution=LIMIT,
       trade_id='c4da537c-1651-4dae-8486-7db30d67b366',
       timestamp=datetime.datetime(2023, 1, 2, 0, 0))]

cancel_order(order_id)

Cancel an existing order by ID.

Parameters:

Name Type Description Default
order_id str

The ID of the order to cancel

required

Raises:

Type Description
ValueError

If no order with the given ID is found

match(timestamp)

Match queued and placed orders in price-time priority.

Parameters:

Name Type Description Default
timestamp datetime

Timestamp of order matching

required

Returns:

Type Description
ExecutedTrades

Executed trades storage object

place(orders)

Place orders without matching.

Parameters:

Name Type Description Default
orders Orders

Orders to place

required

Raises:

Type Description
ValueError

If duplicate order IDs are detected or if an order ID already exists in the book. Note: Cancel orders (Status.CANCEL) are exempt from duplicate ID validation.