Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Order Book Example

This section should feel intentionally different from the blockchain section.

The core lesson is determinism and ordering.

1) Protocol Design

Expose a clean client boundary with gRPC (tonic):

  • SubmitOrder
  • CancelOrder
  • ReplaceOrder
  • MarketDataStream (top-of-book and trades)

Matching rules (spec first)

  • Price priority first.
  • Time priority second (FIFO within a price level).

This mirrors real exchange rulebooks; for example HKEX explicitly describes price-time priority matching: https://www.hkex.com.hk/Services/Trading/Securities/Overview/Trading-Mechanism?sc_lang=en.

LOB terms (quick refresher)

  • Bid: highest buy interest.
  • Ask: lowest sell interest.
  • Spread: best_ask - best_bid.
  • Levels: aggregate resting quantity by price.

Background reading: https://cdn.aaai.org/ojs/9313/9313-13-12841-1-2-20201228.pdf.

Deliverable: order.proto

syntax = "proto3";
package orderbook.v1;

service OrderBook {
  rpc SubmitOrder(SubmitOrderRequest) returns (SubmitOrderResponse);
  rpc CancelOrder(CancelOrderRequest) returns (CancelOrderResponse);
  rpc ReplaceOrder(ReplaceOrderRequest) returns (ReplaceOrderResponse);
  rpc MarketDataStream(MarketDataRequest) returns (stream MarketDataEvent);
}

message SubmitOrderRequest {
  string client_id = 1;
  string symbol = 2;
  Side side = 3;
  uint64 price = 4;
  uint64 qty = 5;
}

message SubmitOrderResponse { string order_id = 1; }
message CancelOrderRequest { string order_id = 1; }
message CancelOrderResponse { bool ok = 1; }
message ReplaceOrderRequest { string order_id = 1; uint64 new_price = 2; uint64 new_qty = 3; }
message ReplaceOrderResponse { bool ok = 1; }
message MarketDataRequest { string symbol = 1; }

message MarketDataEvent {
  oneof event {
    TopOfBook top = 1;
    Trade trade = 2;
  }
}

message TopOfBook { uint64 bid = 1; uint64 ask = 2; }
message Trade { uint64 price = 1; uint64 qty = 2; }
enum Side { SIDE_UNSPECIFIED = 0; BUY = 1; SELL = 2; }