Skip to content
Architecture review · David Mullins

Macro Brief Agent Architecture Review

A personal macro trading system. A data pipeline, a statistics and backtesting engine, a dashboard and an LLM agent track macroeconomic data, the owner's open positions and the theses behind them. Built to improve the owner's trading decisions and keep a checkable record of each one.

Python · PostgreSQL · LLM agents · Model Context Protocol · Data pipelines · Time-series statistics · Backtesting · WebSockets · React · Docker

1Purpose

The owner trades macro theses across rates, credit, equities and commodities. Each thesis is written down with the conditions that mark its entry and exit, and is tracked from the day it is declared. Each data release raises four questions: what moved, whether it bears on a thesis, whether a stated condition was crossed, and whether a stance should change. The system answers them across hundreds of series at every release and records each decision with its reasons.

Agent requirements

  • Every figure must be the right value for the right date, verified before anyone reads it.
  • Claims must come from the thesis and the data, and every stated cause must be one the data shows.
  • The model recommends; the owner decides every stance. Broker access is read-only.

2Design rules

  • Code renders every table and computes every figure. The model writes the commentary on them.
  • Every field the model writes is checked before it is sent. A failing field goes back to the model with the violations listed; after the last attempt it is withheld.
  • Permissions are enforced in infrastructure: database roles, the egress proxy, and credentials held outside the agent container. The prompt repeats the same limits to the model.
  • Facts go out automatically when they pass the checks. Anything with a stance waits for the owner's approval.
  • Every value carries the time it was recorded. Reads take a cutoff and return what was known at that time.

3Architecture

PRODUCTION HOST · PUBLIC PORT: SSH ONLYINTERNAL NETWORK · EXIT VIA PROXYData sourcesFREDYahoo FinanceTradierCFTCCMEIMFUS Treasury TICLBMAWorld Gold CouncilGeopolitical risk index500 signals2.1M observationsScheduleringestion jobsposition marksdigest, 3 a dayhealth checksPostgres 17observations(valid and known time)push factsposition bookagent run recorddrafts and decisionsTelegram recordsNOTIFY on insertand on run stateapi.anthropic.comHTTPS, port 443Egress proxyone host, loggedAgentClaude Code, headlessOpus 5.5own MCP server7 read-only toolsbuilt-ins disabledDashboard servicerebuilds on new dataread-only rolewrites one fileGatewayWebSocket serverreview pageTelegram: sends,reads taps, repliesserves dashboardlocalhost onlyonly way outfor agent outputTelegramowner's phonemessages, taps, repliesboth ways; host polls outReview pageowner's browserthrough SSH tunnelfetchwritesread-onlyown recordHTTPS, both waysone route outnotifications and readsdecisions and deliveriesread-onlyfile
Highlighted: the agent's only exits. The model call leaves through one proxy; the agent's drafts reach a person only through the gateway.
ServiceRole
schedulerIngests the sources above, marks positions, sends the digest three times a day, runs health checks.
dbPostgres 17. The single source of state; a trigger sends a NOTIFY for every new row.
agentDrafts the facts and the analyses after each digest and a daily review; answers the owner's questions.
egressThe agent's only route out: one host, every connection logged.
gatewayLive review page, Telegram delivery and taps, the dashboard. Writes the owner's decisions.
dashboardRebuilds the market dashboard when new data lands.

Data pipeline

  • 500 signals from ten sources and 2.1 million observations, growing with each scheduled fetch. Sources: Federal Reserve economic data (FRED, with ALFRED vintages for revised series), market prices, option chains and quotes, futures positioning, rate expectations, official reserves and capital flows, commodity market data and a geopolitical risk index.
  • The scheduler runs each source near its release time: FRED at 06:45, 12:00 and 17:15 ET on weekdays; prices at 06:45, 12:00 and 16:15; option surfaces at 15:45 and 17:00; CFTC on Saturdays; IMF, TIC and GPR monthly. A job runs once it is due; a long run delays the jobs behind it.
  • Fetches are incremental by series type. A final series, such as a closing price, fetches from its last stored period. A revised series, such as a statistical release, re-fetches a lookback window that covers its revision cycle. A projection is fetched whole. FRED, IMF and TIC also run periodic full re-fetches for benchmark revisions.
  • Each row holds the period it describes and the time this system received it; a read at a cutoff returns what was recorded by then (section 5.1). A revised value for a held period is a new row. A trigger drops an insert that repeats the latest value held. ALFRED rows carry the source's publication date.
  • Seventeen health checks run on every digest and on the dashboard: staleness against each series' own release pattern, a source whose latest run failed, holdings behind what the source publishes, publication-lag conventions, and one unit per series.

4Statistics engine

Derived quantities are computed on read from the stored observations. The engine is asset-agnostic. Adding a series means adding an adapter definition; adding a derived quantity means adding an entry to the metric list.

  • Signals and functions compose into expression trees, evaluated on each input's native observation dates. Each function declares its required history, the minimum observations per window, the input units it accepts, its output unit and a formula version. Validation rejects a unit mismatch before evaluation.
  • Every read names its basis: first prints, the values as originally published, or latest revisions. Tradability claims use first prints; descriptions of what happened use latest revisions. The 1,060-test signal sweep runs on both.
  • 97 watched metrics, reported at every release. They include a credit-cycle phase plane (debt growth against income growth, with a risk-premium axis); the breadth of a price move across currencies, which separates a move in the asset from a move in the dollar; and thematic composites on a rank scale. Each metric states what it measures. Entry and exit levels live in the owner's conditions.
  • Signal research tests whether a signal's trailing change leads a forward return, by rank correlation and quintile spread. Samples are spaced one forward horizon apart, and each grid alignment is scored separately. A leaked-future control and a noise control run before any result is read.
  • Strategy definitions produce per-date verdicts. The backtest engine turns them into trades and an equity curve and models costs separately. Results are judged with block-bootstrap confidence intervals, chance bands and thresholds deflated for the number of tests, all fixed before the evaluation runs.

5Agent flow

SCHEDULERAGENTGATEWAYOWNERdigest push3 a dayfacts runfacts message,sent if checks passreadsanalysis run,every subjectone message, arow per subjectreadsApprove, orReject + reasonverifies the tap,stores the decisionnext analysis readsstance and verdict
Highlighted: the only step that needs a person.
  1. A digest push at 07:00, 12:30 or 17:30 ET, or the 18:30 daily review, starts a run.
  2. Code reads the store at the push's cutoff and renders the tables, the flags, and each subject's factors and conditions (5.1, 5.2).
  3. The model reads that material, queries more through seven read-only tools as needed, and returns a stance and a reading per subject as JSON (5.3).
  4. Checks test every field. A failing field goes back to the model with the violations; one that still fails is withheld (5.4).
  5. The gateway sends the analyses to Telegram with Approve and Reject per subject, and the owner decides each (5.5, 5.6). Facts lines that pass the checks go out automatically. The owner can reply to any message with a question; the agent answers from the same data under the same checks.
  6. The decision is stored and read by that subject's next run.

5.1Inputs: data as recorded at the push

Problem
Macro data is revised after release, and every series publishes on its own clock. An analysis has to be reproducible from what was known at the moment it ran.
Approach
Every observation carries two times: the period it describes and the moment it was recorded. A revision is a new row. Reads take the newest value recorded by a cutoff; a past analysis re-run at its own cutoff gets the same inputs. Each series keeps its own observation dates, and a computation across series uses the span they share. Positions, fills and notes are insert-only, and a correction is a new row.
Result
Past pushes re-run at their own cutoffs reproduced their figures exactly. One set of rows answers what was known at any past moment and what is known now, for every series and for the position book.

5.2Inputs: flags from each series' own noise

Problem
Series differ in volatility, tick size and release frequency. One alert threshold applied to all of them fires too often on some series and too rarely on others.
Approach
Each series' recent change is compared with the upper tail of its own same-length changes over its defined analysis window. A series flags once when it crosses that line and re-arms when it falls back. Slower series flag on every new print. A threshold in the owner's conditions passes two tests: it exceeds the series' own noise, and it is large enough to matter to the position.
Result
One rule covers every series, whatever its units, tick size or frequency. Each flag reports how often its series crossed the line over the window.

5.3The run: read-only tools in a sandbox

AGENT CONTAINER · NON-ROOT · INTERNAL NETWORKRunner (Python)prompt, budgetslockdown checkrun recordclaude -pClaude Code, pinnedbuilt-ins disabledsession in memoryMCP server (stdio)7 read-only toolsPostgressame hostEgress proxyCONNECT, one hostapi.anthropic.commodel inferenceAnthropic-hostedspawnseventstool calls, resultsSELECT only, read-only roleprompts, tool results outmodel outputs backTLS end to end
Highlighted: the only connection that leaves the host. Our host opens it, and it carries both requests and responses. The proxy sees host names and byte counts; TLS runs end to end inside its tunnel.
Problem
An agent needs live portfolio data and tools to explore it. Every tool, network route and credential it holds is a way for it to act.
Approach
Claude Code runs headless on our host, one process per run, with its built-in tools disabled and its system prompt replaced.[4][5] Its tools come from our own MCP server: seven read-only queries under a SELECT-only database role.[6] Before the first turn, the runner compares the session's tool list with the expected list and kills the run on a mismatch. The container's one route out is a proxy that admits a single host.[2] Budgets cap tokens, turns, tool calls and time per run and per day.
Result
The harness logs every tool call with its arguments and a hash of its result, and checks the model's own account of its calls against that log. Every logged call has been on the allowed list.
claude -p --model opus --effort high --tools "" \
  --strict-mcp-config --mcp-config '<our stdio server>' \
  --system-prompt '<ours>' --json-schema '<ours>' \
  --no-session-persistence --permission-prompts none
Reaches the model providerStays on the host
Prompts, the push's tables, theses and positions; tool results; model outputs; the request credential.[1]Database, Telegram and broker credentials. Telemetry, error reports and transcripts are switched off.[1]

5.4Checks before delivery

DETERMINISTICModel outputJSON,per schemaNumberseach one inthe run's recordDatesthe record's datebeside each figureNamesdisplay namesfor every seriesWordingsums refused,exact quotesEventscalendar startand end datesJudgea second modelreads for clarityTierfrom theresultsa violation goes back to the model with the listup to three attempts; a field still failing is withheldauto: sentreview: owner decidesblock: withheld
Problem
A model can write a wrong number, a figure dated to the wrong day, or an unsupported cause inside otherwise well-formed text.
Approach
Code renders every table and computes every figure; the model writes judgement against them. Each field then passes deterministic checks: every number is in the run's record, every figure sits beside the date the record gives it, written arithmetic is refused, quotations match the owner's notes word for word, and event dates match the calendar. A second model reads for clarity, narrative and unsupported stances. Violations go back to the model as a list.
Result
Every delivered number, date, quotation and event date matches the run's record. Known failure cases run as regression tests in CI.

5.5Delivery and review on Telegram

ANALYSIS  push 159  2026-10-26 12:30

moved (7 days; line: 95th pct)
 investment-grade spread  FLAG
   +6bp (line 6bp), 2% of days
 VCLT long corporate ETF
   +2.08% (line 2.27%), 2% of days

next
 due 17:15 ET: 10y Treasury yield, ...
 2026-10-27 to 10-28 (in 1 day): FOMC

investment-grade spread thesis,
declared 2026-10-13, not entered
 stance: WAIT
   Wait. Condition 1 has moved: the
   investment-grade spread read 0.91
   on 2026-10-23, +9bp since 0.82 on
   2026-10-13. Condition 4 still
   stands: VCLT rose +2.08% and LQD
   +1.23% over the 7 days to
   2026-10-26 while the 10y Treasury
   yield went to 4.96 on 2026-10-22.
steepener: ApproveReject
investment-grade spread thesis: ApproveReject
Problem
The owner decides each stance. Each judgement has to reach the owner's phone, take one tap, and leave a record.
Approach
After each push, one Telegram message covers every position and thesis: what moved, the book since the previous close, and what is due. Each subject with new data since its last analysis gets a stance and a short reading with Approve and Reject; the rest get one line from code. Taps are signed, accepted only from the owner's chat and account, and applied once. The gateway reads Telegram by outbound long polling.
Result
Each decision feeds the next analysis of that subject and becomes an evaluation label. A reply to any message is answered as a question, under the same tools and checks.

Dry run on production data, abridged. Code writes everything above the stance; the model writes the reading.

5.6Review page and gateway

Problem
Stream drafts to a browser and take decisions back live, with SSH as the only public port.
Approach
A WebSocket server written from RFC 6455 on asyncio, reached through an SSH tunnel. Postgres NOTIFY signals new rows. Each client has a cursor of what it has received, and a regular poll from that cursor recovers missed notifications. Delivery is at least once, with client-side dedupe and replay on reconnect. Bursts collapse into per-signal summaries, and each client's send queue is bounded. Instances keep all state in Postgres and the client cursor, and close connections with code 1012 on shutdown; clients then reconnect and replay.
Result
A test shuts down one of two instances mid-stream while new rows land. The client reconnects to the other instance and receives exactly the missed rows, once.

5.7Token cost

Problem
A model that looks up and computes its own figures spends its tokens on retrieval and arithmetic, and every figure it computes needs checking.
Approach
Code renders a factor table and each subject's conditions as written. The model writes the judgement.
Result
Moving the figures into code cut the daily review from about 261,000 to about 121,000 tokens (-54%). Every figure in it is checked against the run's record.

6Security

SurfaceControl
Public networkSSH with key authentication is the one public service. Every other service binds to localhost or an internal network.
Review pageReached through an SSH tunnel; WebSocket upgrades checked by Origin; strict content security policy.
TelegramOutbound long polling from one poller. Button data HMAC-signed; taps accepted only from the owner's chat and account.
Model accessInternal network, one-host proxy, telemetry off, session held in memory (section 5.3).
DatabaseSix roles. The agent's role is SELECT-only; positions change through a load script run at the owner's instruction.
BrokerRead-only integration. The broker client has one network method, an HTTP GET with the verb hardcoded.
SecretsGenerated on the host into one mode-600 file per service.

The model call runs on a subscription token whose scope is model requests only.[3][8] Provider retention and controls: [1], [7].

7Failure modes and safeguards

Failure modeSafeguard
A tool result above the harness's size limit is replaced by a preview.[6]Each tool declares its own limit; a preview is logged as a failed call.
A model restates a derived series from its inputs and gets the formula wrong in well-formed text.A date check, a stronger model, and a prompt rule against restating a series as its own definition.
A burst of source revisions produces a message above the channel's size limit.Revisions grouped per signal; the gateway summarises bursts.
The model sees a figure the checker's record lacks, and a correct line is blocked.Everything shown to the model is in the checked record.
A model restates sums or paraphrases inside quotation marks.Code computes the tables; the checks refuse written arithmetic and inexact quotes.

8Key decisions

DecisionWhyCost
Code renders the tablesTable figures are deterministic code outputNew analysis needs new code
Facts automatic, stances reviewedReview time goes to judgement callsA wrong fact ships if every check misses it
Claude Code headless, self-hostedAgent loop, MCP client and structured output built in; data and tools stay on our hostTools are configuration; the runner verifies the lockdown on every start
Own WebSocket and MCP serversAuditable code we own end to endWe maintain the protocol code and its edge cases
Long polling for TelegramOutbound connections onlyOne poller, held by an advisory lock
Production with rollback; throwaway databases for testsOne user; rollback is cheapDry runs on production and throwaway-database tests carry the risk

9Scope and path to industry grade

The Macro Brief Agent is a single-owner research system: one reviewer, one host, one subscription. The controls below carry over at any size; the operating model around them changes.

Carries over

  • Code computes the numbers; checks run before anything is sent.
  • Read-only tools as the agent's full tool set; one exit for agent output.
  • Human approval for every stance; an audit log the harness writes; budgets per run and per day.
  • A stateless gateway: state lives in Postgres and the client cursor.
  • The OWASP Top 10 for LLM Applications risks that apply: prompt injection, excessive agency, sensitive information disclosure, improper output handling, unbounded consumption.

Changes

AreaHereIndustry grade
Model accessSubscription token, consumer termsAPI key or workload identity under commercial terms; zero data retention where eligible
SecretsFiles on the hostSecrets manager, short-lived credentials, automatic rotation
Data to the modelFull theses and positionsClassification; each task receives only the fields it needs
IsolationContainers on one hostVM-level sandbox per run; signed, scanned images
UsersOne ownerSSO, roles, per-user audit, two-person approval for high-impact actions
AvailabilityOne host; nightly dumpsManaged Postgres with replicas; several gateway instances; runs on a job queue; stated RPO and RTO
EvaluationLabels collected from reviewEval suite gating every prompt and model change; judge calibrated against human labels
ObservabilityLogs and the run recordOpenTelemetry traces and metrics; alerts on blocks, budget overruns and refused egress
DeliveryCI on every push (GitHub Actions, Postgres 17, Vitest); owner-approved deploys with tagged rollback imagesContinuous deployment through staging; infrastructure as code; automated rollback

Next

  • Conditions stored as data and evaluated by code, which sets the stances the model may choose from.
  • Measured factor exposures per position, refreshed on a schedule.
  • Check precision and judge agreement measured against the owner's labels.

10Stack

LanguagesPython 3.12, TypeScript, SQL
AI and agentsLLM agents on Claude Code headless; Model Context Protocol server built in-house; tool use; JSON-schema structured output; LLM-as-judge review; human-in-the-loop approval; evaluation labels from review; token budgets
Data engineeringETL from ten REST and file sources; incremental loads and backfills; bitemporal PostgreSQL schema with point-in-time reads; data-quality checks; schema migrations
Statistics and researchTime-series analysis; signal screening; backtesting; block bootstrap; multiple-testing correction; factor betas per position
Backendasyncio, asyncpg; WebSockets (RFC 6455); Postgres LISTEN/NOTIFY; advisory locks; Telegram Bot API
FrontendReact 19, TypeScript, Vite
InfrastructureDocker Compose on a Linux VPS; egress proxy; SSH as the only public surface; least-privilege database roles; one secrets file per service
QualityAbout 600 tests (pytest, Vitest); database tests on throwaway Postgres in CI (GitHub Actions); dry runs against production with writes off

References

  1. Claude Code docs, Data usage: data flow, telemetry services, training policy, retention, encryption.
  2. Claude Code docs, Enterprise network configuration: proxy variables and network access requirements.
  3. Claude Code docs, Authentication: long-lived tokens, credential precedence.
  4. Claude Code docs, Run Claude Code programmatically: -p, structured output, stream events, unattended runs.
  5. Claude Code docs, CLI reference: flags.
  6. Claude Code docs, MCP: stdio servers, output limits, maxResultSizeChars.
  7. Claude Code docs, Security; Anthropic Trust Center.
  8. Claude Help Center, Use the Claude Agent SDK with your Claude plan.
Private research system with read-only broker access. Not investment advice. Figures from production, unaudited. © 2026 David Mullins.