Playground
The whole of diaspar, compiled to WebAssembly: its evaluator, its REPL and its standard library. Pick a program or write your own, then press Ctrl + Enter. Nothing leaves your machine: the program runs in this tab, with a file system that lives in memory and no network.
;; A tiny stock exchange of actors. Every order goes through one exchange, ;; so the order book needs no locks; each trader's money is an account of ;; its own; an auditor checks the books at the closing bell. An actor is a ;; function from its state and a message to its next state, and it sends ;; with the effect Send. The scheduler here delivers one message at a time, ;; in the order they were sent, so every run is the same, and it runs ;; anywhere, the browser included. (use std.atom) (use std.term) (defenum Side Buy Sell) ;; The three protocols: what the exchange, an account and the auditor take. (defenum Order (Limit [trader side qty price]) (Close [audit])) (defenum Fill (Traded [side qty price]) (Settle [audit])) (defenum Report (LastPrice [price]) (Holding [trader cash shares])) (defeffect Send [to message]) (defn send [to message] (perform (Send to: to message: message))) (defn account-of [trader] #[:account trader]) ;; Colors that read on a dark ground: buys green, sells red, trades gold. (defn side-style [side] (if (= side Side.Buy) "#7ee787" "#ff7b72")) ;; ---- the exchange ---- ;; bids: highest price first, then oldest; asks: lowest first, then oldest. (deftype Resting [trader qty price]) (defn crosses? [side best price] (if (= side Side.Buy) (<= best.price price) (>= best.price price))) (defn exchange [state message] (match message (Order.Limit trader: side: qty: price:) (let [buy (= side Side.Buy) other (if buy Side.Sell Side.Buy) _ (term.print (term.styled f"{trader:<5} {(if buy "buys " "sells")} {qty:>3} @ {price}" (side-style side))) ;; Trade against the other side of the book while the prices cross. #[book left last] (loop [book (if buy state.asks state.bids) left qty last state.last] (let [best (first book)] (if (or (= left 0) (nil? best) (not (crosses? side best price))) (break #[book left last]) (let [size (min left best.qty)] (term.print (term.styled f" ✓ {size} @ {best.price} with {best.trader}" "#e3b341")) (send (account-of trader) (Fill.Traded side: side qty: size price: best.price)) (send (account-of best.trader) (Fill.Traded side: other qty: size price: best.price)) (continue (if (= size best.qty) (vec (rest book)) (assoc book 0 (assoc best :qty (- best.qty size)))) (- left size) best.price))))) state (assoc (if buy (assoc state :asks book) (assoc state :bids book)) :last last :traders (conj state.traders trader))] (if (= left 0) state ;; The rest waits behind every order at the same or a better price. (let [own (if buy state.bids state.asks) behind? (fn [r] (if buy (< r.price price) (> r.price price))) at (or (first (for [#[i r] (map-indexed vector own) when: (behind? r)] i)) (count own)) placed (into (conj (vec (take at own)) (Resting trader: trader qty: left price: price)) (drop at own))] (term.print (term.styled f" rests {left}" "#8b949e")) (assoc state (if buy :bids :asks) placed)))) ;; The exchange settles the accounts itself, so every Traded it sent ;; reaches an account before its Settle does. (Order.Close audit:) (do (term.print f"[bold]closing bell; unfilled: {(count state.bids)} buy, {(count state.asks)} sell[/]") (send audit (Report.LastPrice price: state.last)) (for [trader (sort state.traders)] (send (account-of trader) (Fill.Settle audit: audit))) state))) ;; ---- an account ---- (defn account [state message] (match message (Fill.Traded side: qty: price:) (let [sign (if (= side Side.Buy) 1 -1)] (assoc state :shares (+ state.shares (* sign qty)) :cash (- state.cash (* sign qty price)))) (Fill.Settle audit:) (do (send audit (Report.Holding trader: state.trader cash: state.cash shares: state.shares)) state))) ;; ---- the auditor ---- (defn auditor [state message] (match message (Report.LastPrice price:) (assoc state :price price) (Report.Holding trader: _ cash: _ shares: _) as: row (let [rows (conj state.rows row)] (when (= (count rows) state.traders) (term.print f"\n[bold]{"trader":<6} {"cash":>7} {"shares":>6} {"worth":>7}[/]") (for [(Report.Holding trader: cash: shares:) (sort-by (fn [r] r.trader) rows)] (print f"{trader:<6} {cash:>7,} {shares:>6} {(+ cash (* shares state.price)):>7,}")) (let [cash (sum (for [r rows] r.cash)) shares (sum (for [r rows] r.shares)) ok (and (= cash state.cash) (= shares state.shares))] (term.print (term.styled f"cash conserved: {(= cash state.cash)}, shares conserved: {(= shares state.shares)}" (if ok "#7ee787" "#ff7b72"))))) (assoc state :rows rows)))) ;; ---- the scheduler ---- ;; Delivers messages one at a time, oldest first: an actor's behavior gets ;; its state and the message, and what it sends joins the queue. (defn run [actors queue] (loop [actors actors queue queue] (if (empty? queue) (break actors) (let [#[to message] (first queue) #[behave state] (get actors to) sent (atom.new #[]) next (handle (behave state message) (Send to: message:) [resume] (do (atom.swap! sent conj #[to message]) (resume nil)))] (continue (assoc actors to #[behave next]) (into (vec (rest queue)) @sent)))))) (def traders #[#["ada" 5000 20] #["bob" 3000 60] #["cy" 8000 0]]) (def orders #[#["bob" Side.Sell 30 102] #["ada" Side.Sell 10 101] #["cy" Side.Buy 25 100] #["cy" Side.Buy 20 102] #["bob" Side.Sell 20 99] #["ada" Side.Buy 15 98]]) (defn main [args] (let [actors (into #{:exchange #[exchange #{:bids #[] :asks #[] :last 0 :traders #set[]}] :auditor #[auditor #{:price 0 :rows #[] :traders (count traders) :cash (sum (for [#[_ c _] traders] c)) :shares (sum (for [#[_ _ s] traders] s))}]} (for [#[name cash shares] traders] #[(account-of name) #[account #{:trader name :cash cash :shares shares}]]))] (run actors (conj (vec (for [#[trader side qty price] orders] #[:exchange (Order.Limit trader: trader side: side qty: qty price: price)])) #[:exchange (Order.Close audit: :auditor)])) nil))
Output appears here when you run the program.
REPL
A session that stays alive. Load the program above into it, call its functions one at a time, and define them again while the rest keeps what it has.