Skip to content

CALF Market-Data Gateway Protocol Training

Objective

Train on end-to-end usage of the CALF protocol through pm-md-gwy using the example parser/subscriber libraries for external market-data consumers.

You will practice connection, subscription, snapshots, live market-data consumption, heartbeats, replay checkpoints, and recovery/error behavior.

Background reading

Prerequisites

  • Chapters 01-23 completed.
  • Engine running and producing market activity.
  • pm-md-gwy running and reachable on TCP (default 5570).
  • pm-calf-spy installed (ships with the edumatcher package — no separate build step).
  • Support libraries and clients available in docs/examples/calf:
  • calf_parser.py, calf_subscriber.py
  • calf_parser.h, calf_parser.c, calf_subscriber.c

Recommended startup terminals:

  1. Engine: pm-engine --verbose
  2. CALF gateway: pm-md-gwy
  3. One or more client terminals for subscriber exercises

Where the example files are, and port 5570

As in the previous chapter, docs/examples/calf exists in a repository checkout; on a container or pipx install use EX=$(python -c "from edumatcher.config_deploy import examples_root; print(examples_root().parent)") and $EX/calf/…. The C example needs make and a C compiler (not in the container image). If the AI-simulation container is running, its own pm-md-gwy already holds port 5570. Start pm-md-gwy a few seconds after the engine and before the first client: a client started too early gets Connection refused. This chapter's configuration has no market makers. To create a trade, enter a limit sell from TRADER01 and a limit buy at the same price from TRADER02 (as in the previous chapter). In a container shell, use the tcp helper of chapter 23 wherever this chapter says nc 127.0.0.1 5570.

Background

CALF is a line-oriented protocol over TCP used for external market-data dissemination. Clients connect to pm-md-gwy, perform HELLO and SUB, then consume stream data.

In this chapter, the most important operational ideas are:

  • Session establishment with HELLO and WELCOME, including per-symbol reference data (REF=SYM:DEC) for display precision
  • Channel and symbol subscription with SUB and UNSUB, across all seven channels: TOP, TRADE, STATE, INDEX, DEPTH, AUCTION, CB
  • Baseline snapshots (SNAP) plus incremental live events (MD, TRADE, STATE, AUCTION, INDIC, CB)
  • Liveness with HB and PING/PONG
  • Replay with the standalone RESUME command / LASTSEQ, and REPLAY_MISS handling
  • Auction uncross results (AUCTION, with a REASON for what kind of uncross it was) and indicative pricing during the call phase (INDIC)
  • Circuit-breaker detail (CB), including its cause (SRC) and Automated Corridor Expansion (CORRLO/CORRHI/EXP, closing backstop prints)
  • pm-calf-spy as the ready-made, read-only way to inspect any of the above without writing a client

Exercise 1: Prepare a Config That Enables CALF

Generate engine_config.yaml with a market_data_gateway section:

pm-config-gen \
  --symbols AAPL MSFT \
  --participants TRADER01 TRADER02 OPS01:ADMIN \
  --sessions-enabled \
  --market-data-gateway \
  --market-data-bind-address 127.0.0.1 \
  --market-data-port 5570 \
  --market-data-replay-window-sec 30 \
  --market-data-heartbeat-interval-sec 1 \
  --market-data-idle-timeout-sec 5 \
  --output engine_config.yaml --force

Back up, check, deploy — then restart

This chapter starts from a fresh configuration (its operator is OPS01), and --force replaces your engine_config.yaml: save a copy first if you want to come back to it (cp engine_config.yaml engine_config.before-ch24.yaml). As always, nothing changes until you deploy it and restart the engine: pm-cverifier engine_config.yaml, then pm-config-deploy engine_config.yaml. Sessions are enabled, so the restarted engine starts in CLOSED: open the market from the operator console (pm-admin --id OPS01, then SESSION|STATE=PRE_OPEN and SESSION|STATE=CONTINUOUS).

Start or restart processes with that config:

pm-engine --verbose
pm-md-gwy -v

With -v the gateway ends its startup with listening on 127.0.0.1:5570 (engine_pub=… index_pub=…) (0.0.0.0 in the container, as in chapter 23).

Checkpoint: gateway starts and listens on the configured port.

Exercise 2: Use the Python Example as a TOP/TRADE Consumer

From the example directory. calf_subscriber.py has no --channels flag — it always subscribes to the Cartesian product of {TOP, TRADE, STATE, DEPTH} (filtered down to whatever WELCOME|CH_SUPPORTED= actually advertises) for the symbols you pass:

cd docs/examples/calf
python3 calf_subscriber.py \
  --host 127.0.0.1 \
  --port 5570 \
  --symbols AAPL

Then make a trade. Observe:

  • a baseline for each stream first: TOP AAPL …, and STATE session -> CONTINUOUS — the subscriber also adds a session-wide SUB|CH=STATE|SYM=* (pass --no-state-wildcard to skip it)
  • then, live, TOP, DEPTH and TRADE lines; each trade carries its durable trade ID (TRADE AAPL 000019-000000001 40 @ 150.00 (BUY))

STATE is one of the four channels that accept SYM=* (with TOP, TRADE and AUCTION); DEPTH, INDEX and CB always need a symbol. A STATE subscription for one symbol still hears about session-wide changes: on every open, close or phase change the gateway also sends a STATE line for each symbol that is not halted.

Checkpoint: subscriber prints parsed MD/TRADE events with expected symbol, sequence, and durable trade ID fields.

Exercise 2B: Manual Handshake Probe with nc

Before continuing with richer clients, validate a minimal manual protocol flow:

nc 127.0.0.1 5570

Then send:

HELLO|CLIENT=manual01|PROTO=CALF1
SUB|CH=TOP,TRADE|SYM=AAPL
SYMBOLS

Expected behavior:

  • WELCOME|PROTO=CALF1|GW=md-gwy01|HBINT=1|REPLAY=30|EPOCH=…|CH_SUPPORTED=…|SYMBOLS=AAPL,MSFT|REF=AAPL:2,MSFT:2 after HELLO, then an HB line every second (HBINT=1)
  • SNAP|CH=TOP|SYM=AAPL|… after SUB (TRADE has no snapshot: a print that already happened has no "current state")
  • SYMBOLS|COUNT=2|SYMBOLS=AAPL,MSFT|REF=AAPL:2,MSFT:2 after SYMBOLS
  • live MD and TRADE once market activity occurs

REF=SYM:DEC is each symbol's display precision (tick_decimals) — the one piece of reference data a market-data client cannot discover from the prices themselves. It rides the handshake rather than every line.

Every TRADE line carries a durable TRADE_ID and its RUN_SEQ. Keep the trade ID when recording the tape: a RESUME response can overlap live traffic, and two lines with the same TRADE_ID are the same execution even when their delivery sequence differs.

Checkpoint: manual nc session can establish, subscribe, and receive at least one live market-data line.

Optional Exercise 3: Use the C Example Subscriber

This C exercise requires make and a C compiler, which are not installed in the container image. Skip it there, or build it on a host with those tools. Exercise 2's Python subscriber provides the same market-data client workflow.

Build and run the C subscriber:

cd docs/examples/calf
make
./calf_subscriber 127.0.0.1 5570

Observe in output:

  • WELCOME fields
  • SUB flow
  • MSG lines for live traffic

Optional checkpoint: C subscriber connects, parses, and prints live CALF events.

Exercise 3B: pm-calf-spy — the Read-Only Diagnostic CLI

calf_subscriber.py/.c are example libraries to build on; pm-calf-spy is a ready-made, read-only diagnostic client for watching the wire directly, with no code to write. It runs fully passively — no reconnect, no auto-recovery, no local state rebuild — so what you see is exactly what the gateway sent, nothing injected or inferred on your behalf.

pm-calf-spy --channels TOP,TRADE --symbols AAPL

Try a few variations:

# Every channel the gateway advertises, every symbol (default)
pm-calf-spy

# JSON output instead of human-readable
pm-calf-spy --channels TOP,TRADE --symbols AAPL --format json

# Show heartbeats too (suppressed by default)
pm-calf-spy --channels STATE --symbols AAPL --show-heartbeats

# Raw wire line alongside the formatted one
pm-calf-spy --channels TOP --symbols AAPL --raw

# One-shot replay of a single stream
pm-calf-spy --resume TOP:AAPL:1042 --channels TOP --symbols AAPL

# Stop after 20 data-carrying lines
pm-calf-spy --channels TRADE --symbols '*' --count 20

Now try the wildcard default against a mix of eligible and ineligible channels:

pm-calf-spy --channels '*' --symbols '*'

Since SYM=* is only valid for TOP/TRADE/STATE/AUCTION, a naive single SUB|CH=*|SYM=* would be rejected by the gateway. pm-calf-spy subscribes the wildcard-eligible channels and leaves the others out, saying so:

◆ skipping CB, DEPTH, INDEX — these channels reject SYM=*; pass --symbols with explicit symbols to watch them

Checkpoint: you can explain why pm-calf-spy runs with reconnect and auto-recovery both off, and why --channels '*' --symbols '*' doesn't produce a rejected SUB.

Exercise 4: Auction Results and Circuit-Breaker Detail

Two channels extend the original five: AUCTION (auction uncross results — no baseline SNAP, SYM=* allowed, mirrors TRADE) and CB (circuit-breaker halt/resume detail — cached baseline SNAP, SYM=* not allowed, mirrors DEPTH/INDEX). calf_subscriber.py does not drive these two channels, so exercise them manually with nc, alongside STATE for comparison:

nc 127.0.0.1 5570
HELLO|CLIENT=manual03|PROTO=CALF1
SUB|CH=CB,STATE|SYM=AAPL
SUB|CH=AUCTION|SYM=AAPL

Expected behavior:

  • immediate SNAP|CH=CB|SYM=AAPL|STATUS=ACTIVE|... on subscribe (or STATUS=HALTED plus detail if already halted; if the gateway was started after the halt, the detail is only LEVEL, RESUMEAT and SRC) — AUCTION gets no SNAP, same as TRADE
  • an AUCTION|... line the next time AAPL's auction uncrosses (open, close, or a re-opening auction after a halt), carrying EQPX/EQQTY/TRADES and, if a residual exists, IMBSIDE/IMBQTY, plus a REASON of SCHEDULED (leaving an auction/other non-matching phase), REOPEN (a halted symbol reopening), or RECOVERY (GTC orders restored at engine startup) — without REASON the three would be indistinguishable on the wire
  • a CB|... line on the next halt (STATUS=HALTED with LEVEL and SRC; a breaker halt adds TRIGGERPX, REFPX and RESUMEAT) and a matching one on resume (STATUS=ACTIVE with SRC) — SRC is CB for an automatic breaker trigger or ADMIN for an operator halt; it says what caused the halt, not how it will resume
  • a STATE|... line for the same halt/resume, independently — compare the two: STATE gives you the simple SESSION=HALTED/SESSION=CONTINUOUS flag, CB gives you the operational detail behind it. They fire independently, not in a guaranteed order relative to each other

This configuration has no circuit breaker (chapter 11), so cause the halt yourself from the operator console: HALT_SYM|SYM=AAPL, then RESUME_SYM|SYM=AAPL. Expected (TS= fields left out):

STATE|CH=STATE|SYM=AAPL|SEQ=4|SESSION=HALTED|PREV=CONTINUOUS
CB|CH=CB|SYM=AAPL|SEQ=2|STATUS=HALTED|LEVEL=ADMIN_SYMBOL|SRC=ADMIN
AUCTION|CH=AUCTION|SYM=AAPL|SEQ=2|EQQTY=0|TRADES=0|IMBQTY=0|REASON=REOPEN
STATE|CH=STATE|SYM=AAPL|SEQ=5|SESSION=CONTINUOUS|PREV=HALTED
CB|CH=CB|SYM=AAPL|SEQ=3|STATUS=ACTIVE|SRC=ADMIN

The resume runs a reopening auction, which had nothing to cross. Then send SUB|CH=CB|SYM=* and confirm it is rejected with ERR|CODE=INVALID_SYMBOL|SYM=* — unlike AUCTION, TOP, TRADE, and STATE, CB never accepts a wildcard symbol.

Checkpoint: you can explain why AUCTION has no SNAP but CB does, why CB rejects SYM=* while AUCTION accepts it, and what each AUCTION|REASON= value tells you that the rest of the fields don't.

Exercise 4B: Indicative Auction Price (INDIC)

While an opening or closing auction's call phase is running, the gateway publishes a repeated indicative uncross price on the same AUCTION channel — a different message type, INDIC, not a preview of AUCTION itself. It says what would happen if the phase ended right now, not what did happen.

nc 127.0.0.1 5570
HELLO|CLIENT=manual04|PROTO=CALF1
SUB|CH=AUCTION|SYM=AAPL

Clear AAPL (CANCEL_SYM|SYM=AAPL) and move the market into its closing auction from the operator console (SESSION|STATE=CLOSING_AUCTION), then observe:

  • repeated INDIC|CH=AUCTION|SYM=AAPL|... lines during the call phase, on a fixed interval (auction_indicative_interval_sec, default 1s) — every reading republishes, even unchanged ones, so a client can tell a stable indicative from a stalled feed
  • INDICQTY and IMBQTY always present; INDICPX omitted when the book would not cross at all — that omission is a reading ("nothing would trade"), not a gap
  • exactly one final AUCTION|... line when the call phase ends. An uncross with no crossing interest is reported too, as EQQTY=0|TRADES=0; you will see one at every opening and closing auction, and for a reopening after a halt. To get a non-empty one, enter a crossing sell and buy while the call phase is open (a sell of 50 at 149.50 from TRADER01 and a buy of 40 at 151.00 from TRADER02); the indicative then reads INDICQTY=40|IMBQTY=10|INDICPX=149.5|IMB=SELL|PHASE=CLOSING_AUCTION, and SESSION|STATE=CLOSED ends the call phase with AUCTION|…|EQQTY=40|TRADES=1|IMBQTY=10|REASON=SCHEDULED|EQPX=149.5|IMBSIDE=SELL. Reopen the market (PRE_OPEN, then CONTINUOUS) before you go on.

Checkpoint: you can explain why INDIC and AUCTION share a channel but are different message types, and why a missing INDICPX must not be rendered as a zero price.

Automated Corridor Expansion on the CB channel

A circuit-breaker halt does not always end at its first RESUMEAT. If the indicative price at that moment is outside the reopening corridor (CORRLO..CORRHI), the halt is extended: CB sends another STATUS=HALTED with EXP one higher, a later RESUMEAT, a wider corridor and the INDICPX/INDICQTY/IMB that failed. No STATE line goes with it — the symbol was halted before and after. A halt still running at the close ends with STATUS=ACTIVE|REASON=CLOSING_BACKSTOP|CLAMPED=1|PRINTPX=…: the exchange printed at the corridor's edge, not at a price the book found. This needs a breaker and a lopsided book to see live; the Risk Controls chapter of the Operator's Guide describes it in full. A client that ignores EXP and the corridor will report a halted symbol as overdue to reopen.

Exercise 5: Protocol Control Messages (PING, UNSUB, EXIT)

Use netcat for manual control-message testing:

nc 127.0.0.1 5570

Then send lines:

HELLO|CLIENT=manual02|PROTO=CALF1
SUB|CH=TOP|SYM=AAPL
PING
UNSUB|CH=TOP|SYM=AAPL
EXIT

Expected behavior:

  • PING yields PONG|TS=…
  • UNSUB removes delivery for that stream, with no reply of its own
  • EXIT closes the session: the gateway sends nothing more and closes the connection (with the tcp helper, press Ctrl-C to get your prompt back)

Checkpoint: you can manually drive and verify control flow.

Exercise 6: Replay and Recovery with RESUME

  1. Start a subscriber and note the highest SEQ for (TOP, AAPL), and the EPOCH= on its WELCOME.
  2. Disconnect client.
  3. Generate additional market activity.
  4. Reconnect with a plain HELLO, then send RESUME for that stream:
HELLO|CLIENT=replay01|PROTO=CALF1
RESUME|CH=TOP|SYM=AAPL|LASTSEQ=<saved_seq>|EPOCH=<saved_epoch>

RESUME is a command in its own right, sent after WELCOME, and repeatable — send one per stream you were following. EPOCH names the gateway run your LASTSEQ came from: sequences begin again at 1 when pm-md-gwy restarts, so a RESUME with an old run's epoch is answered REPLAY_MISS, however far the new run's stream has got. Restart pm-md-gwy between steps 2 and 4 to see it.

Observe replay behavior:

  • replayed events for SEQ greater than LASTSEQ when retained. This chapter's configuration keeps only 30 seconds of replay history (--market-data-replay-window-sec 30), so do steps 1–4 promptly; a RESUME|CH=TOP|… for events older than that is answered with REPLAY_MISS (try LASTSEQ=1 after a minute to see it) and TRADE shows how a replay hit looks
  • REPLAY_MISS plus a SNAP baseline when outside the replay window — but on TOP/STATE/INDEX/DEPTH/CB only. On TRADE and AUCTION no SNAP follows, because there is no snapshot of a print that already happened.

  • Now repeat step 4 on TRADE instead of TOP, with a LASTSEQ several messages behind. Count the prints you receive against the ones you had already seen.

The reply carries everything past LASTSEQ, not just what you missed — including the message that revealed the gap. Work out what a tape would look like if the client rendered them all, then read how docs/examples/calf/calf_subscriber.py avoids it.

Checkpoint: you can describe recovery for both replay-hit and replay-miss cases, say which channels get a SNAP on a miss, and explain why a replay reply must be de-duplicated.

Exercise 7: Error Conditions and Operational Interpretation

Test typical protocol errors with malformed lines:

SUB|CH=TOP|SYM=AAPL                 (before HELLO)
HELLO|CLIENT=x|PROTO=BAD
SUB|CH=UNKNOWN|SYM=AAPL
SUB|CH=DEPTH|SYM=*                  (invalid wildcard usage — DEPTH requires an explicit symbol)
SUB|CH=CB|SYM=*                     (invalid wildcard usage — CB requires an explicit symbol)

The answers, in order: ERR|CODE=AUTH_REQUIRED|DETAIL=send HELLO first, ERR|CODE=AUTH_REQUIRED|DETAIL=CLIENT/PROTO required, then (after a valid HELLO) ERR|CODE=INVALID_CHANNEL|CH=UNKNOWN and twice ERR|CODE=INVALID_SYMBOL|SYM=*. A handshake error closes the connection, so start a new session for each of the first two. SUB|CH=TOP|SYM=* is accepted, and answered with one SNAP per symbol.

Map observed ERR codes to operator action:

  • AUTH_REQUIRED: client handshake bug or ordering error, or a HELLO with a missing CLIENT or wrong PROTO
  • INVALID_CHANNEL: unsupported CH value
  • INVALID_SYMBOL: unknown symbol, or SYM=* used with INDEX/DEPTH/CB
  • REPLAY_MISS: requested resume point outside replay retention
  • RATE_LIMITED: client is sending commands too fast; throttle it
  • SUB_LIMIT: too many subscriptions on one session; subscribe more narrowly
  • SLOW_CLIENT: the consumer could not keep up; its backlog was dropped and the session closed — reconnect and use RESUME (Exercise 6)

A session the gateway ends for inactivity gets EXIT|REASON=idle_timeout before the socket closes.

Checkpoint: you can convert each ERR code into a practical remediation step.

Support Libraries and Example Clients

Reference implementations used in this training chapter:

  • docs/examples/calf/calf_parser.py
  • docs/examples/calf/calf_subscriber.py
  • docs/examples/calf/calf_parser.h
  • docs/examples/calf/calf_parser.c
  • docs/examples/calf/calf_subscriber.c
  • pm-calf-spy (installed CLI — no source to read, but the fastest way to point at a running gateway and see the wire)

Use these to bootstrap both quick lab subscribers and production-like integration test harnesses. Note that calf_subscriber.py/.c only drive TOP, TRADE, STATE, and DEPTH (filtered by WELCOME|CH_SUPPORTED=) — they do not touch AUCTION, INDIC, or CB. Reach for pm-calf-spy or a manual nc session for those, as this chapter's exercises do.

Summary

You have now covered major CALF protocol usage patterns:

  • provisioning configuration with pm-config-gen
  • connecting external clients through example libraries, and through the read-only pm-calf-spy CLI
  • handling channel/symbol subscriptions and snapshots across all seven channels
  • distinguishing channels with a baseline SNAP (TOP, STATE, INDEX, DEPTH, CB) from those without one (TRADE, AUCTION, INDIC)
  • reading auction uncross results (AUCTION, with REASON), indicative pricing during a call phase (INDIC), and circuit-breaker operational detail (CB, with SRC and Automated Corridor Expansion) alongside the simpler STATE halt/resume flag and its per-symbol session fan-out
  • discovering per-symbol display precision via REF
  • using control messages and liveness probes
  • recovering with RESUME/LASTSEQ semantics, including de-duplicating a replay
  • correlating each public print by its durable TRADE_ID across replay overlap
  • diagnosing protocol errors operationally

Reflection

You have now used both RALF (Chapter 23, post-trade dissemination: CLEARING/DROP_COPY/AUDIT roles) and CALF (this chapter, market-data dissemination: TOP/TRADE/state channels). Before moving on, answer this synthesis question:

If you were building a downstream system, which protocol would you consume and why — a risk system that needs to know every fill as it happens, a market-data terminal displaying live top-of-book, and a compliance archive that reconstructs the day's activity after the fact? For each of those three consumers, state whether it needs RALF, CALF, or both, and justify your answer using what each protocol actually carries (trade/clearing events vs. price/quote state) rather than just their names.

Further Reading