monoblok docs
Docs menu · Market data

Examples

Market data

These examples process market data using rounding, deduplication, JSON field extraction and OHLC bars.

Price ticker#

Intermediate Two rules and an export. Prices arrive on MARKET.<SYM>; subscribers get a deduplicated mirror, and big jumps are fanned out to an alerts subject that is forwarded to a real NATS server.

examples/ticker.edn
; Market ticker: clean up noisy prices and alert on big jumps.

; Round to 3 decimals, drop duplicates, emit on MARKET.<SYM>.stable.
(on "MARKET.*"
  (-> payload-float
      (round 3)
      (squelch)
      (publish! (subject-append "stable"))))

; Fan out big jumps (>= 1.0 move between consecutive ticks) to
; alerts.market.<SYM>. delta is 0 on first sight so this stays quiet
; until we have a prior value.
(on "MARKET.*"
  (when (>= (abs (delta payload-float)) 1.0)
    (publish!
      (subject-with "alerts.market" (subject-token 1))
      payload)))

; Forward all market alerts to the remote NATS server.
(export
  :servers ["nats://127.0.0.1:4222"]
  :name    "monoblok-ticker"
  :export  ["alerts.market.>"])
soundcheck · examples/ticker.edn
in   MARKET.AAPL  182.3401
out  MARKET.AAPL.stable  182.34
in   MARKET.AAPL  182.3402
in   MARKET.AAPL  182.351
out  MARKET.AAPL.stable  182.351
in   MARKET.AAPL  183.9
out  MARKET.AAPL.stable  183.9
out  alerts.market.AAPL  183.9

delta returns the difference from the previous value on the same subject (0 on first sight), so the alert rule stays quiet until it has a prior price. (subject-token 1) pulls the symbol out of MARKET.AAPL to build a per-symbol alert subject. The export form forwards only alerts.market.>; the raw ticks and the stable mirror stay local.

OHLC bars#

Intermediate bar! folds samples into open / high / low / close bars per symbol, closing either every N ticks or on wall-clock boundaries.

examples/bars.edn
; OHLC bars over a market feed.
;
; Producers publish raw prices on MARKET.<SYM> (e.g. MARKET.AAPL "182.34").
; A bar closes either every 60 ticks per symbol or every wall-clock minute,
; depending on the window descriptor. On close, `bar` emits four sub-subjects:
;   MARKET.AAPL.bar.open   first price in the bar
;   MARKET.AAPL.bar.high   max price seen
;   MARKET.AAPL.bar.low    min price seen
;   MARKET.AAPL.bar.close  last price seen in the bar
;
; State is per call site, subject, and window kind, so each ticker builds its
; own bars and tick + time forms keep distinct slots. The in-progress
; bar is part of the snapshot, so a restart mid-bar resumes without
; losing the open / high / low collected so far. Time bars also close
; from the server's clock walker if a window elapses without a new tick.

; Tick bars: every 60 trades, regardless of how long that takes.
; :reentrant is only needed because the rule below consumes the derived
; MARKET.<SYM>.bar.close stream in the same patchbay. The bar subjects
; do not match MARKET.*, so this does not feed the bar builder back into
; itself.
(on "MARKET.*" :reentrant true
  (bar! 60 payload-float))

; Wall-clock bars, aligned to whole minutes. Useful when you want a
; clean per-minute chart row regardless of trade rate.
;(on "MARKET.*"
;  (bar! :ms 60000 payload-float))

; Downstream alerting can sit on the closed-bar stream and stay clean of
; intra-bar noise. Example: alert if the bar's close jumps by >= 1.0
; from the prior bar's close on the same symbol.
(on "MARKET.*.bar.close"
  (when (>= (abs (delta payload-float)) 1.0)
    (publish! (subject-with "alerts.market" (subject-token 1)) payload)))

The bar rule is :reentrant true only because the second rule consumes the derived MARKET.<SYM>.bar.close stream. Alerting on closed bars instead of raw ticks keeps the alert free of intra-bar noise. A subscriber to MARKET.AAPL.bar.> sees a burst of four messages per closed bar, in open / high / low / close order. In-progress bars are part of the snapshot, so a restart mid-bar resumes without losing the open, high and low collected so far.

shell
examples/bars.sh

A market data firehose#

Advanced This example splits JSON market data frames into scalar subjects, then applies price filters and alert rules. Subscribers select the fields they need by subject.

The json-massive example simulates a Massive-shape websocket feed (stocks, options, crypto, forex). It has two pieces: mock_producer.js, a synthetic producer that speaks the NATS protocol over a plain socket and publishes frames on subjects shaped <ev>.<symbol>, and massive.edn, the patchbay below. There is more background in the blog post.

For stock trades the whole conditioning layer is three rules, each feeding the next:

  1. (json-demux! ...) on T.* splits the frame into one subject per field: T.AAPL.p (price) and T.AAPL.s (size).
  2. A rule on the demuxed T.*.p rounds to 2dp, drops duplicates and mirrors to T.<SYM>.p.stable.
  3. A second rule on T.*.p alerts on a jump of 1.00 or more between consecutive ticks on the same symbol.

Rule 2 matches T.*.p, a subject that only exists because rule 1 emitted it. That works because rule 1 is marked :reentrant true. The same wildcard also matches options (T.O:AAPL250620C00200000), and crypto and FX repeat the pattern with their own thresholds.

examples/json-massive/massive.edn
; Demux Massive JSON frames into per-field scalar subjects. Re-entry (depth
; cap 8) lets the downstream rules below match the demuxed subjects.
;
; AM / XA / CA carry server-side OHLC bars, so we just demux them. For
; bar-from-tick logic on a raw trade stream, see examples/bars.edn.

; --- Stocks ----------------------------------------------------------------

; Stock trade: T.<SYM> -> { p, s, ... }
(on "T.*" :reentrant true
  (json-demux! "p" "s" payload))

; Stock NBBO quote: Q.<SYM> -> { bp, bs, ap, as, ... }
(on "Q.*"
  (json-demux! "bp" "bs" "ap" "as" payload))

; Stock minute aggregate: AM.<SYM> -> { o, h, l, c, v, vw, ... }
(on "AM.*"
  (json-demux! "o" "h" "l" "c" "v" "vw" payload))

; --- Options (same T/Q ev letters as stocks, OCC symbol with O: prefix) ----
; The "T.*"/"Q.*" rules above already cover options because the wildcard
; matches "T.O:AAPL250620C00200000" too. Nothing extra needed here.

; --- Crypto ----------------------------------------------------------------

(on "XT.*" :reentrant true
  (json-demux! "p" "s" payload))

(on "XQ.*"
  (json-demux! "bp" "bs" "ap" "as" payload))

(on "XA.*"
  (json-demux! "o" "h" "l" "c" "v" "vw" payload))

; --- Forex -----------------------------------------------------------------

; Forex quotes use single-letter b/a (no sizes). Demux those.
(on "C.*" :reentrant true
  (json-demux! "b" "a" payload))

(on "CA.*"
  (json-demux! "o" "h" "l" "c" "v" payload))

; --- Cleanup pipelines (consume demuxed subjects via re-entry) -------------

; Stock trade prices: round to 2dp, drop duplicates, mirror to .stable.
(on "T.*.p"
  (-> payload-float
      (round 2)
      (squelch)
      (publish! (subject-append "stable"))))

; Alert on big single-trade price jumps (>= 1.0 between consecutive ticks
; on the same symbol). delta is 0 on first sight so this stays quiet
; until we have a prior value.
;
; (subject-token 1) pulls the Nth dot-separated token from the matched
; subject (0-indexed), so for "T.AAPL.p" it returns "AAPL". Used here
; (and in the crypto/fx rules below) to build a per-symbol alert subject.
(on "T.*.p"
  (when (>= (abs (delta payload-float)) 1.0)
    (publish!
      (subject-with "alerts.trade" (subject-token 1))
      payload)))

; Crypto prices move bigger; alert on >= 1% moves between trades.
(on "XT.*.p"
  (when (>= (abs (/ (delta payload-float) payload-float)) 0.01)
    (publish!
      (subject-with "alerts.crypto" (subject-token 1))
      payload)))

; Forex mid-rate alert: a 5 pip move on a major is notable. Computed off
; the demuxed bid; cheap proxy for "the market moved".
(on "C.*.b"
  (when (>= (abs (delta payload-float)) 0.0005)
    (publish!
      (subject-with "alerts.fx" (subject-token 1))
      payload)))

Five frames through the trade and crypto rules:

soundcheck · examples/json-massive/massive.edn
in   T.AAPL  {"ev":"T","sym":"AAPL","p":187.421,"s":100}
out  T.AAPL.p  187.421
out  T.AAPL.p.stable  187.42
out  T.AAPL.s  100
in   T.AAPL  {"ev":"T","sym":"AAPL","p":187.424,"s":50}
out  T.AAPL.p  187.424
out  T.AAPL.s  50
in   T.AAPL  {"ev":"T","sym":"AAPL","p":188.95,"s":200}
out  T.AAPL.p  188.95
out  T.AAPL.p.stable  188.95
out  alerts.trade.AAPL  188.95
out  T.AAPL.s  200
in   XT.BTC-USD  {"p":64000,"s":0.1}
out  XT.BTC-USD.p  64000
out  XT.BTC-USD.s  0.1
in   XT.BTC-USD  {"p":64700,"s":0.2}
out  XT.BTC-USD.p  64700
out  alerts.crypto.BTC-USD  64700
out  XT.BTC-USD.s  0.2

The second AAPL trade rounds to the same 187.42, so the stable mirror stays quiet. The third moves 1.526 and raises alerts.trade.AAPL. The second BTC trade is a 1.08% move and raises alerts.crypto.BTC-USD.

A subscriber to T.*.p.stable receives rounded prices by symbol without parsing the original JSON frames.

Run it#

shell
# terminal 1: start monoblok with the demuxing patchbay
# if you don't need the last-value cache, save some cpu by turning it off
monoblok --no-lvc examples/json-massive/massive.edn

# terminal 2: start the producer (RATE=2 doubles the message rate)
node examples/json-massive/mock_producer.js

# terminal 3: peek at everything
nats sub '>'

Or let the script do all three for five seconds and print tables of the raw frames, the demuxed prices, the stable mirror and the alerts side by side:

shell
./examples/json-massive/run.sh

Last prints for slow markets and the close#

A dashboard opening on Sunday afternoon wants to render the last print for every symbol it tracks. Nothing is publishing, the market is closed, and the patchbay has been idle for two days. Opt the stable mirror into the last-value cache:

EDN
(lvc ["T.*.p.stable"])

Subscribe to $LVC.T.*.p.stable and the broker hands back the most recent rounded price for every symbol it has seen, then nothing else until trading resumes. The same subscribe works for a logger restarting mid-session, or a tool that wants the last print on a thinly-traded name where ticks arrive minutes apart. The cache stores the latest rounded price; squelch suppresses repeated publications of that value.

Already-aggregated channels#

The AM / XA / CA channels deliver server-side OHLC bars on delayed feeds, so the patchbay demuxes those frames into scalar o / h / l / c / v streams instead of recomputing bars from raw trades. If you only have a trade stream and need to build bars locally, use bar!.

Bridging to NATS#

Subscribers can connect directly to monoblok, or receive processed market data through an existing NATS cluster. Add an export form pointing at T.*.p.stable and JetStream on the far side stores the deduplicated, rounded prices, not the raw firehose:

EDN
(export
  :servers ["nats://nats.internal:4222"]
  :name    "monoblok-market"
  :export  ["T.*.p.stable" "alerts.>"])

A remote stream configured for these subjects stores rounded prices and alerts. Replayed messages have the same payload format as live output. Raw frames remain available to local subscribers.

Budgeting bar state#

Advanced bar! is cheap per subject, but it is stateful. A local bar builder keeps one in-progress bar slot for every distinct market/symbol subject the rule has seen. Thousands of symbols across tens of markets can therefore turn into tens or hundreds of thousands of long-lived slots.

examples/json-massive/bar-cardinality.edn
; High-cardinality `bar!` memory probe for Massive-style trade streams.
;
; This is deliberately separate from massive.edn. The normal Massive example
; demuxes AM / XA / CA aggregate frames that already contain bars. This file is
; for the case where raw trades arrive as JSON and monoblok builds local bars.
;
; Subjects use T.<MARKET>.<SYM> so the measurement script can scale both
; market count and symbol count:
;
;   T.M00.S00001|{"ev":"T","sym":"S00001","p":100.25,"s":10}
;
; The bar tick window is intentionally huge. The point of the probe is not
; closed-bar output; it is the long-lived in-progress bar slot allocated for
; every distinct trade subject.

(on "T.*.*"
  (when (json-get "p" payload)
    (bar! 100000000 (json-get "p" payload))))

The harness drives that patchbay through --soundcheck and reports max RSS:

shell
# defaults: MARKETS=20 SYMBOLS=5000 TICKS=1 BAR_WINDOW=100000000
examples/json-massive/measure-bar-cardinality.sh

# scale the subject universe and keep bars open longer
MARKETS=50 SYMBOLS=10000 TICKS=1 BAR_WINDOW=1000000000 examples/json-massive/measure-bar-cardinality.sh

The important dimension is MARKETS * SYMBOLS: increasing TICKS mostly reuses existing slots, while increasing the subject universe creates more retained patchbay state. The same reasoning applies to every stateful form: narrow the filter when you can, and measure the shape you plan to run.

MIT licensed · © 2026 Alex Reid
Lexvica offers solutions built with monoblok.