Files
eventbook-exchange/matching.py
T

53 lines
1.6 KiB
Python

"""Pure price/time matching for one instrument; prices are integer cents."""
from dataclasses import dataclass
@dataclass
class Order:
seq: int
account: str
side: str
price: int
remaining: int
@dataclass(frozen=True)
class Fill:
bid: Order
ask: Order
price: int
quantity: int
def match(orders, *, opening=False):
bids = sorted((o for o in orders if o.side == "buy"), key=lambda o: (-o.price, o.seq))
asks = sorted((o for o in orders if o.side == "sell"), key=lambda o: (o.price, o.seq))
if not bids or not asks or bids[0].price < asks[0].price:
return []
clearing = None
if opening:
# Evaluate every permitted tick, including ticks between submitted prices.
def priority(price):
demand = sum(o.remaining for o in bids if o.price >= price)
supply = sum(o.remaining for o in asks if o.price <= price)
return (-min(demand, supply), abs(demand - supply), price)
clearing = min(range(101), key=priority)
fills = []
b = a = 0
while b < len(bids) and a < len(asks):
bid, ask = bids[b], asks[a]
if bid.price < ask.price:
break
if clearing is not None and not ask.price <= clearing <= bid.price:
break
price = clearing
if price is None:
price = bid.price if bid.seq < ask.seq else ask.price
qty = min(bid.remaining, ask.remaining)
fills.append(Fill(bid, ask, price, qty))
bid.remaining -= qty
ask.remaining -= qty
b += bid.remaining == 0
a += ask.remaining == 0
return fills