Tutorial — a trading floor with brote

Build a live OCaml trading floor step by step, from its matching engine and event log to a brote client and cluster.

What we'll build

The trading floor is a brote application with a price-time matching engine that streams to many browsers at once. This tutorial describes it layer by layer: the pure domain, the shared wire protocol, the application service, the WebSocket connection, and the brote client.

The finished application: two browser clients connect to different nodes of a three-node araara cluster while a thousand simulated traders place orders and post chat messages. The market and chat converge across the cluster.

What the screen shows: a live quotes table, a sector heatmap with top movers, an order ticket, your private portfolio with mark-to-market P/L, a trades tape, a leaderboard, and a chat panel.

The trading floor dashboard: live quotes table, controls, order ticket, portfolio, trades, leaderboard and chat
The application is one brote client. Each number is a reactive derivation of a synced collection. The page is rendered in the browser.

The example is in the brote repository under examples/trading-floor. To build and run it:

$ dune build
$ dune exec examples/trading-floor/bin/main.exe

Then open http://localhost:8080. The dune build also compiles the browser client to JavaScript and promotes it next to the stylesheet, so there is no separate bundler step.

The shape of the application

The diagram shows the layering before the code. The arrows are ordinary function calls and one socket connection.

browser ── POST /api/orders ──▶ floor_web ──▶ Floor.Exchange.place
                                                  │
                                                  ▼
                                        Order.Book.execute   (pure: match → events)
                                                  │  events
                                                  ▼
                                     project → Portfolio + Market + tape
                                                  │
                                                  ▼
                                        Brote.Sync.Server  (read models)
                                                  │  one multiplexed WebSocket
                                                  ▼
browser ◀──────────── brote_web client (per-key signals patch the DOM)

The domain (order, portfolio, market, chat) is pure and compiles to native code and to JavaScript. The wire protocol (floor_wire) is shared by both ends. The application service (floor) connects the pure core to its callers. floor_web is the hcs server. client/ is the brote browser app. The sections below describe them in that order.

Step 1 — the domain: an event-sourced order book

The Order context defines commands and events as types, and its main entry point is one pure function:

type command =
  | Place of {
      id : Ids.Order_id.t;
      trader : Trader_id.t;
      side : side;
      limit : Price.t;  (* buy: max price to pay; sell: min price to accept *)
      qty : Qty.t;
    }
  | Cancel of { id : Ids.Order_id.t; trader : Trader_id.t }

type event =
  | Order_accepted of { id; trader; side; limit; qty; seq }
  | Trade_executed of trade   (* names both parties, price and qty *)
  | Order_resting of { id; trader; side; limit; remaining; seq }
  | Order_filled of { id }
  | Order_cancelled of { id; trader }

The book is the aggregate, with one instance per symbol. It forms the consistency boundary for that symbol. Its execute function takes a command and returns the updated book with events, without performing side effects:

val execute : t -> Events.command -> (t * Events.event list, Events.reject) result
(** For a [Place]: [Order_accepted], a [Trade_executed] (and [Order_filled]) per
    fill in strict price-time priority, then [Order_resting] for any
    non-marketable remainder. Each fill is at the maker's resting price. *)

execute is pure. Its result depends on its inputs, so the matching rules can be property-tested. The same engine runs on the server and can also run in the browser. Money is integer cents throughout, and prices are integers. The rest of the system consumes events. Portfolio and Market project from Trade_executed and do not read the book directly.

Step 2 — the shared wire protocol

floor_wire is compiled to native code and to JavaScript, so the server and the browser share one definition of each message. The read-model DTOs are records with [@@deriving brote_json]. A quote is split by how often each part changes: static listing data is sent once, and dynamic tick data is sent as it changes:

type listing = { ticker : string; name : string; sector : string; prev_close : int }
[@@deriving brote_json]

type tick = {
  last : int;  (* last trade price, cents *)
  bid : int;  (* best bid in cents, 0 when empty *)
  ask : int;  (* best ask in cents, 0 when empty *)
}
[@@deriving brote_json]

Each live feed is an App descriptor, which pairs a name with its key and value codecs. Both ends refer to the same descriptor, so the key and value types come from one definition:

let value to_json of_json = App.Value.make ~to_json ~of_json

let listings = App.stream ~name:"floor.listings" ~key:App.Key.string ~value:(value listing_to_json listing_of_json) ()
let quotes   = App.stream ~name:"floor.quotes" ~key:App.Key.string ~value:(value tick_to_json tick_of_json) ()
let chat     = App.collection ~name:"floor.chat" ~key:App.Key.string ~value:(value chat_msg_to_json chat_msg_of_json) ()
let control  = App.command ~name:"floor.control" ~value:(value control_to_json control_of_json) ()

The boundary parser converts raw input into a typed value. An order arrives as JSON and becomes a domain command, or the parser returns a typed error. Code after the parser receives the typed command:

let parse_order json =
  let ( let* ) = Result.bind in
  let req name = function Some x -> Ok x | None -> Error ("bad " ^ name) in
  let* r = order_request_of_json json in
  let* trader = req "trader" (Trader_id.of_string r.trader) in
  let* symbol = req "symbol" (Symbol.of_string r.symbol) in
  let* side = req "side" (Events.side_of_string r.side) in
  let* qty = req "qty" (Qty.of_int r.qty) in
  let* limit = req "limit" (Price.of_cents r.limit) in
  Ok { trader; symbol; side; limit; qty }

Step 3 — the application service

Floor.Exchange connects the pure domain to its callers. It owns the canonical state (a book per symbol and a portfolio per trader) and the Brote.Sync.Server read models that stream to browsers. It has two entry points. The ungated submit runs a command and projects the events it returns:

let submit t ~symbol cmd =
  match Book.execute (get_book t symbol) cmd with
  | Error _ -> []
  | Ok (book', evs) ->
      Hashtbl.replace t.books (Symbol.to_string symbol) book';
      project t symbol book' evs;
      evs

The gated place is the path used by API callers. It checks spot solvency first. This data-dependent invariant is checked in place rather than in the pure book. It then calls submit and summarizes the fill:

let place t ~(parsed : Wire.parsed) : Wire.order_response =
  let pf = get_portfolio t parsed.Wire.trader in
  let affordable =
    match parsed.Wire.side with
    | Events.Buy -> Money.compare pf.Portfolio.cash (Money.cost parsed.Wire.limit parsed.Wire.qty) >= 0
    | Events.Sell -> Portfolio.position_qty pf parsed.Wire.symbol >= Qty.to_int parsed.Wire.qty
  in
  if not affordable then Wire.Rejected_response { reason = "insufficient funds" }
  else begin
    (* … run submit, total the fills, answer Accepted_response … *)
  end

The simulator supplies market activity. It is a liquidity model. On each tick it submits a burst of random valid limit orders through the same submit workflow that an order from a person takes. Prices come from matching those orders.

let step t =
  if Atomic.get t.running then begin
    let r = Atomic.get t.rate and vol = Atomic.get t.volatility in
    let per_tick = max 1 (r / tick_hz) in
    (* … pick a random symbol, jitter the last price by volatility, … *)
    (*     build a valid Place from smart constructors, and submit it … *)
  end

let run_worker t ~clock =
  Exchange.seed t.exchange;             (* opening liquidity *)
  let dt = 1. /. float_of_int tick_hz in
  let rec loop () = Eio.Time.sleep clock dt; step t; loop () in
  loop ()

The two sliders at the top of the screen (orders per second and volatility) set these two atomics while the application runs:

The controls increase volatility and the order rate. The table updates because the simulator submits orders to the matching engine rather than following a scripted price feed.

Step 4 — multiplexing streams over one WebSocket

The live data travels over a single WebSocket, multiplexed by Brote.Net.Mux into named channels. The server attaches each Sync.Server to a channel and routes inbound control commands and chat back through the same connection:

let handler ~exchange ~sim ~room ~router ws =
  Brote_hcs.serve ws ~setup:(fun transport ->
      let mux = Mux.create transport in
      let q = Mux.channel mux "q" in
      let detach_q = Sync.Server.attach (Exchange.quotes_server exchange) ~send:q.T.send () in
      q.T.on_message (fun raw ->
          match App.decode_command Wire.control raw with Some c -> Sim.apply_control sim c | None -> ());
      let me = Mux.channel mux "me" in
      me.T.on_message (fun trader -> Portfolio_router.subscribe router ~trader ~send:me.T.send |> ignore);
      let c = Mux.channel mux "c" in
      let client = Collab.Server.attach (Chatroom.room room) ~send:c.T.send in
      c.T.on_message (Collab.Server.receive (Chatroom.room room) client);
      fun () -> detach_q (); Collab.Server.detach (Chatroom.room room) client)

Six channels share one socket: q quotes, p leaderboard, t trades, l listings, me the trader's own portfolio (delivered privately), and c chat. The endpoint consists of the static plug for the bundle and CSS, the router for the page and order API, and this WebSocket handler:

let build ~clock ~place_order ~exchange ~sim ~room ~static_dir =
  let router = Portfolio_router.create ~exchange in
  Hcs.Endpoint.create Hcs.Endpoint.default_config
  |> Hcs.Endpoint.with_plug (Hcs.Plug.Static.create static_dir)
  |> Fun.flip Hcs.Endpoint.router (Router.routes ~clock ~place_order)
  |> Fun.flip Hcs.Endpoint.websocket (Socket.handler ~exchange ~sim ~room ~router)

Security caveat (demo). The trader identity on the me channel, like the trader field on POST /api/orders, is client-asserted and unauthenticated. Here, private means that the data is sent on a separate channel. It is not access-controlled. An application that needs access control should authenticate the connection and derive the trader id from the session in a pipeline plug, rather than taking it from the payload.

Step 5 — the browser client

The client is layered: a pure view library (formatting and aggregates, unit-tested outside the browser), a data layer that owns the socket, and presentational panels. main.ml sets the trader identity and the layout:

let () =
  Random.self_init ();
  let me = Printf.sprintf "trader-%04d" (Random.int 10000) in
  run @@ fun () ->
  let feeds = Feeds.connect ~me in
  let selected = S.source "" in
  main [ class_ "app floor" ]
    [
      Panels.controls feeds;
      div [ class_ "grid" ]
        [
          section [ class_ "maincol" ] [ Panels.dashboard feeds ~selected; Panels.stripe feeds ];
          aside [ class_ "side" ]
            [ Panels.ticket feeds ~selected; Panels.portfolio feeds; Panels.tape feeds; Panels.leaderboard feeds; Panels.chat feeds ];
        ];
    ]

The data layer

Feeds.connect opens one WebSocket, multiplexes it, and connects each channel to a typed stream or collection. The private portfolio is delivered after the client announces its trader id on Open:

let connect ~me =
  let base = Ws.transport (Ws.same_origin ()) in
  let mux = Mux.create base in
  let listings = connect_stream ~transport:(Mux.channel mux "l") Wire.listings in
  let quotes = connect_stream ~transport:(Mux.channel mux "q") Wire.quotes in
  let board = connect_stream ~transport:(Mux.channel mux "p") Wire.leaderboard in
  let tape = connect_stream ~transport:(Mux.channel mux "t") Wire.trades in
  let chat = connect_collection ~transport:(Mux.channel mux "c") Wire.chat in
  let me_tr = Mux.channel mux "me" in
  let portfolio = S.source None in
  me_tr.T.on_message (fun raw ->
      match Result.bind (Json.decode_string raw) Wire.portfolio_of_json with
      | Ok pf -> S.set portfolio (Some pf) | Error _ -> ());
  base.T.on_status (fun st -> if st = T.Open then me_tr.T.send me);
  { me; quotes; listings; board; tape; chat; my_portfolio = S.get portfolio }

Ws.transport reconnects on its own. A reconnect is a new connection, so the server sends its snapshot again and the client resyncs.

The live quotes table

The dashboard is a keyed table: one row per ticker, each row bound to its own per-key signal. When a tick changes, the cells of that row are patched. The other 239 rows, and any selection or focus, are not changed.

let dashboard (feeds : Feeds.t) ~selected =
  table [ class_ "stocks" ]
    [
      thead [] [ tr [] [ th [] [ txt' "Symbol" ]; (* … *) ] ];
      el_dyn "tbody" []
        (keyed (Sync.Client.entries feeds.quotes) ~key:Fun.id ~render:(fun ticker tk_sig ->
             Components.quote_row ~on_select:(S.set selected) ticker (let+ tk = tk_sig in Quotes.join feeds ticker tk)));
    ]

This follows the rule from the brote reference. The table structure is built once, and keyed varies the row values. The sector stripe derives from the same joined quotes:

A sector heatmap with per-sector percentage change, alongside top gainers and top losers
The heatmap and movers derive from the quotes signal with View.sector_summary and View.top_movers, and they are recomputed incrementally as ticks arrive.

The order ticket and your portfolio

Clicking a row sets the shared selected signal; the ticket derives its limit from the live last price plus a slippage percentage, then POSTs to /api/orders. The fill arrives over the portfolio and trades streams. The HTTP response is the synchronous acknowledgement.

The order ticket showing a selected symbol, quantity and slippage fields, Buy and Sell buttons, and a fill result line
The order ticket. The result line is the server's acknowledgement; the position itself appears in the portfolio panel.

Placing an order updates the portfolio and the trades tape when the fill arrives:

A symbol and quantity are selected, then the order is bought. The fill is matched on the server and streams back into the private portfolio (with mark-to-market P/L) and the public trades tape.
The private portfolio panel showing cash and two positions with quantity, average price, last price and profit/loss
The portfolio is delivered over the me channel. P/L is marked to the live last price by joining positions with the quotes feed.

The portfolio view joins your positions against the live quotes to compute P/L per row:

let portfolio (feeds : Feeds.t) =
  section [ class_ "panel" ]
    [
      h3 [] [ txt' "Your portfolio" ];
      el_dyn "div" [ class_ "pf" ]
        (let+ pf_opt = feeds.my_portfolio and+ _ = Quotes.all feeds in
         match pf_opt with
         | None -> [ p [ class_ "muted" ] [ txt' "No trades yet — pick a row and Buy." ] ]
         | Some pf -> (* cash + a row per position, P/L marked to the last price *) [ … ]);
    ]

The trades tape and leaderboard

Both panels derive from a synced collection by taking its values, sorting them, truncating the list, and rendering the result. The tape is ordered newest first. The leaderboard is ordered by net worth, with the current trader's row highlighted.

The trades tape listing recent fills with symbol, quantity, price and side
The trades tape lists fills in public, with buys and sells colour-coded.
let tape (feeds : Feeds.t) =
  section [ class_ "panel" ]
    [ h3 [] [ txt' "Trades" ];
      el_dyn "ul" [ class_ "tape" ]
        (let+ rows = Sync.Client.values_signal feeds.tape in
         rows |> List.map snd
         |> List.sort (fun (a : Wire.trade_row) b -> compare b.seq a.seq)
         |> View.take 14
         |> List.map (fun r -> (* one <li> per trade *) …)) ]

CRDT chat

Chat is the multi-writer collection in this application, and it uses a Brote.Collab client. Each browser can set a message, and replicas converge with last-writer-wins, including across cluster nodes. Posting goes through the chat domain's smart constructor, which holds the rules for a valid message.

A message is posted to the trader chat. The log is a CRDT. Messages converge across connected clients and, when the application is clustered, across cluster nodes.
let post_chat t ~text =
  match Chat.Message.create ~author:t.me ~text ~ts:(now_ms () /. 1000.) with
  | None -> false
  | Some m ->
      let id = Printf.sprintf "%013.0f-%04d" (now_ms ()) (Random.int 10000) in
      Collab.Client.set t.chat id { Wire.author = m.author; text = m.text; ts = m.ts };
      true

Step 6 — running the application and calling the API

With the application running on http://localhost:8080, the order API is a JSON endpoint that can be called without the browser:

$ curl -s localhost:8080/api/orders -H 'content-type: application/json' -d '{"trader":"curl-bot","symbol":"AAA","side":"buy","qty":10,"limit":40000}'

The handler only deals with transport. It reads the body and passes it to the injected place_order, which the composition root supplies:

let place ~place_order req =
  let reject reason = Brote_hcs.Json.respond (Wire.order_response_to_json (Wire.Rejected_response { reason })) in
  match Brote_hcs.Json.read req with
  | Error _ -> reject "malformed json"
  | Ok json -> Brote_hcs.Json.respond (Wire.order_response_to_json (place_order json))

Step 7 — going multi-node

Adding brote_hive replication in the composition root turns the single-node application into a cluster. The domain, the wire protocol, and the client do not change. Joining a hive.cluster.swim node and replicating the collections takes these lines:

ignore (Brote_hive.replicate_collection Wire.chat ~server:(Floor.Chatroom.room room) ~node ~name:"floor-chat");
ignore (Brote_hive.replicate_stream Wire.quotes ~server:(Floor.Exchange.quotes_server exchange) ~node ~name:"floor-quotes");
ignore (Brote_hive.replicate_stream Wire.trades ~server:(Floor.Exchange.trades_server exchange) ~node ~name:"floor-trades");

Chat is a CRDT, so it converges on each node. The market streams replicate from a single owner (a Placement singleton runs the simulator and the authoritative book on one node), and a non-owner routes each order to the owner and receives the fill on the replicated streams. To run two nodes:

$ # node 1 (seed / owner)
$ MARKET_CLUSTER_ADDR=127.0.0.1 MARKET_CLUSTER_PORT=5000 PORT=8080 dune exec examples/trading-floor/bin/main.exe
$ # node 2
$ MARKET_CLUSTER_ADDR=127.0.0.1 MARKET_CLUSTER_PORT=5001 MARKET_CLUSTER_SEEDS=127.0.0.1:5000 PORT=8081 dune exec examples/trading-floor/bin/main.exe

Opening one browser on :8080 and another on :8081 gives the clustered setup shown in the video at the top of this page.

Where to go next

The application consists of a pure, event-sourced domain, a wire protocol shared by both ends, an application service that projects events into read models, one multiplexed socket, and a layered brote client derived from synced state. The brote reference covers the library surface behind it: Signal, Net, Sync, Collab, the adapters, and the ppx. The frontend guide describes where brote fits next to araara's default hypermedia frontend. The buildable source is in the brote repository.