m/market labResearch, with a record.
Source on GitHub ↗

itch_fixtures.py

1"""Synthetic ITCH frames and an independent order-book reference model."""23import struct45def common(kind, locate=7, timestamp=1):6    return kind.encode() + struct.pack(">HH", locate, 0) + timestamp.to_bytes(6, "big")789def stock(name):10    return name.encode().ljust(8, b" ")111213def frame(payload):14    return struct.pack(">H", len(payload)) + payload151617def directory(name="TEST", locate=7, timestamp=1):18    return frame(common("R", locate, timestamp) + stock(name) + b"Q" + b"N" +19                 struct.pack(">I", 100) + b"N" + b"C" + b"  " + b"P" +20                 b"N" + b"N" + b"1" + b"N" + struct.pack(">I", 1) + b"N")212223def add(order, side, shares, price, name="TEST", kind="A", locate=7, timestamp=2):24    payload = (common(kind, locate, timestamp) + struct.pack(">Q", order) +25               side.encode() + struct.pack(">I", shares) + stock(name) +26               struct.pack(">I", price))27    if kind == "F":28        payload += b"ABCD"29    return frame(payload)303132def reduce(kind, order, shares, locate=7, timestamp=3, match=123):33    payload = common(kind, locate, timestamp) + struct.pack(">QI", order, shares)34    if kind == "E":35        payload += struct.pack(">Q", match)36    elif kind == "C":37        payload += struct.pack(">Q", match) + b"Y" + struct.pack(">I", 999900)38    return frame(payload)394041def delete(order, timestamp=4):42    return frame(common("D", 7, timestamp) + struct.pack(">Q", order))434445def replace(old, new, shares, price, timestamp=5):46    return frame(common("U", 7, timestamp) + struct.pack(">QQII", old, new, shares, price))474849def reference_row(orders, frame_number, timestamp, kind, depth_limit):50    """Rebuild price totals from live orders instead of maintaining price maps."""51    sides = {"B": {}, "S": {}}52    for side, shares, raw_price in orders.values():53        levels = sides[side]54        levels[raw_price] = levels.get(raw_price, 0) + shares55    bids = sorted(sides["B"].items(), reverse=True)56    asks = sorted(sides["S"].items())5758    def formatted(raw_price):59        return f"{raw_price // 10000}.{raw_price % 10000:04d}"6061    def depth_text(levels):62        return "|".join(f"{formatted(p)}:{shares}" for p, shares in levels[:depth_limit])6364    return {65        "frame": str(frame_number), "timestamp_ns": str(timestamp), "type": kind,66        "bid": formatted(bids[0][0]) if bids else "",67        "bid_shares": str(bids[0][1]) if bids else "",68        "ask": formatted(asks[0][0]) if asks else "",69        "ask_shares": str(asks[0][1]) if asks else "",70        "bid_levels": str(len(bids)), "ask_levels": str(len(asks)),71        "bid_depth": depth_text(bids), "ask_depth": depth_text(asks),72    }73