Architecture Deep Dive
End-to-end request flow through the MarketIntell brain engine — from HTTP to prose, across stocks, options, and crypto.
Architecture Deep Dive
This document traces the exact lifecycle of a single API call through the entire MarketIntell system. We follow one request — POST /v1/chat { "message": "What's the price of BTC?" } — from the moment it hits the HTTP server to the moment a JSON response leaves.
The same pipeline handles crypto and US equities (stocks + options). A domain classifier routes each query to the appropriate domain plugin, which provides domain-specific keyword maps, data providers, tension rules, and identity prompts. The core reasoning engine (CoT pipeline, LLM write, correlation) is shared across domains. Routing fans out across 26 specialists drawing on 27+ external services.
Every function name, file path, and code flow described here is real. This is engineering documentation, not an overview.
Visual Flow
HTTP Request
│
▼
┌─────────────────────────────────────┐
│ Middleware Chain │
│ CORS → Auth → Rate Limit → Quota │
└─────────────┬───────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Brain Router │
│ Domain Guard → Session → Plan │
└─────────────┬───────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Domain Classifier │
│ Auto-detect: crypto │ us_equities │
│ (or use explicit `domain` field) │
└─────────────┬───────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Domain Loader │
│ Load domain plugin: │
│ keywords, providers, tensions, │
│ identity prompt │
└─────────────┬───────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Classifier (0ms) │
│ Keyword Match → Token/Ticker │
│ Extract → Intent Detection │
│ → QueryPlan │
└─────────────┬───────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Data Gather (500-3000ms) │
│ 30 concurrent slots, cached, │
│ retried, health-checked │
│ │
│ Crypto: CoinGecko, CoinGlass, │
│ Binance, Nansen │
│ Equities: FinancialDatasets.ai, │
│ TwelveData, Massive/Polygon │
└─────────────┬───────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Gap Detect + Supplementary Fetch │
│ Critical gaps? → Retry providers │
│ Still gaps? → ReAct loop │
└─────────────┬───────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ CoT Pipeline (Steps 1-4: ~0ms) │
│ │
│ 1. EXTRACT → FactTable (25 facts) │
│ 2. TENSIONS → Contradictions │
│ 3. RESOLVE → Direction+Confidence │
│ 4. THESIS → Structured blueprint │
│ │
│ + Regime, Multi-Agent, Alpha, │
│ Gap Report, Episodic Memory │
└─────────────┬───────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ LLM Write (2-8s) — ONLY LLM CALL │
│ Claude Opus 4 / GPT-5.4 fallback │
│ Direction LOCKED. Must cite facts. │
└─────────────┬───────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Post-processing │
│ Feedback → Memory → Reflection │
│ → Model ELO → Cost Tracking │
└─────────────┬───────────────────────┘
│
▼
JSON Response1. HTTP Layer
File: apps/api/src/api/server.ts
The Hono server receives POST /v1/chat. Before the request reaches any business logic, it passes through the middleware chain in this exact order:
| Order | Middleware | What it does |
|---|---|---|
| 1 | CORS | Validates Origin header against allowlist |
| 2 | Compression | Gzip/Brotli if Accept-Encoding supports it |
| 3 | Body limit | Rejects payloads > 2 MB |
| 4 | Auth | Validates X-API-Key header, loads account tier (free, pro, enterprise) |
| 5 | Rate limiter | Per-key sliding window, tier-based limits |
| 6 | Daily quota | free = 20/day, pro = 500/day, enterprise = unlimited |
| 7 | Usage tracking | Logs API call metadata (key, path, timestamp) |
| 8 | Request ID | Assigns X-Request-ID header for tracing |
Route Resolution
// server.ts
app.route("/v1", brainRoutes);This matches our /v1/chat path and hands off to the brain routes.
File: apps/api/src/api/routes/brain.ts
brainRoutes.post("/chat", async (c) => {
const body = ChatRequestSchema.parse(await c.req.json());
// ...
});The body is validated with Zod's ChatRequestSchema:
const ChatRequestSchema = z.object({
message: z.string(),
session_id: z.string().uuid().optional(),
stream: z.boolean().optional(),
});For our request, this produces: { message: "What's the price of BTC?" } — no session, no streaming.
2. Brain Router
File: src/brain/router/brain.ts
The route handler calls the brain router's entry point:
const result = await queryBrain(message, sessionId, { tier });(For SSE streaming requests, streamBrain() is called instead — covered in Section 10.)
Three things happen before any analysis begins:
2a. Domain Classification
Before the domain guard, the router determines which domain plugin to use. If the request includes an explicit domain field (crypto or us_equities), that's used directly. Otherwise, the domain classifier auto-detects based on the query:
- Crypto signals: crypto token symbols (BTC, ETH, SOL), keywords like "on-chain", "DeFi", "funding rate"
- Equities signals: stock tickers (AAPL, NVDA, MSFT), keywords like "earnings", "P/E ratio", "SEC filing", "options chain"
The selected domain plugin provides the keyword maps, provider configurations, tension rules, and LLM identity prompt used throughout the rest of the pipeline.
2b. Domain Guard — isOffTopic()
A fast check that rejects queries outside the supported domains (crypto and equities). "What's the best pizza in NYC?" gets a polite refusal here. "What's the price of BTC?" and "AAPL trade setup" both pass immediately.
2c. Session Management — ensureSession(sessionId)
Creates a new session or fetches an existing one from Postgres. Since our request has no session_id, a new UUID is generated and a session row is inserted.
2d. Message Persistence — addMessage()
await addMessage(sessionId, { role: "user", content: message });The user's raw message is persisted to the session's message history. This enables multi-turn conversations and episodic memory.
With housekeeping done, the router proceeds to planning.
3. Planning
File: src/brain/engine/planner.ts
const plan = await planQuery("What's the price of BTC?");planQuery() calls classifyQuery() from the classifier, then enriches the result into a full QueryPlan.
The Classifier
File: src/brain/router/classifier.ts
Classification uses a 3-tier system. It tries the cheapest method first and only escalates if needed:
Tier 1 — Keyword matching (fast path, 0ms, no LLM):
The classifier scans the query against KEYWORD_MAP loaded from the active domain plugin (crypto or equities). Each domain provides its own keyword → specialist mappings. For crypto, the word "price" maps to ["price_movement"] specialist. For equities, keywords like "earnings" map to ["fundamental"] and "options chain" maps to ["quantitative"]. Match found — no LLM call needed.
Tier 2 — Regex + symbol list for token extraction:
extractTokens() (crypto) or extractTickers() (equities) scans for asset symbols using regex patterns and a known symbol list. For crypto, "BTC" matches directly. For equities, "AAPL" or "NVDA" match against a US stock ticker list. A stopwords filter prevents false positives on common words like "ME", "IS", "IT".
Tier 3 — Timeframe extraction:
extractTimeframe() looks for time keywords ("daily", "weekly", "1h", etc.). Our query has none, so it defaults to "4h".
The classifier returns:
{
specialists: ["price_movement"],
tokens: ["BTC"],
timeframe: "4h",
intent: "keyword_match"
}Planner Enrichment
Back in planQuery(), two things happen:
-
Specialist name mapping — Legacy names are mapped to current ones:
price_movement → technical -
Intent detection —
detectIntent()runs pattern matching across 15+ intents in priority order. The word "price" matchesprice_analysis.
The final QueryPlan:
{
tokens: ["BTC"],
specialists: ["technical"],
timeframe: "4h",
intent: "price_analysis",
rawQuery: "What's the price of BTC?"
}4. Data Gathering
File: src/brain/engine/gather.ts
const data = await gatherData(plan);This is the parallel data fetching engine. It operates under two hard constraints:
- 45-second global timeout — the entire gather phase must complete within this window
- 30 concurrent request limit — a semaphore (
acquireSlot/releaseSlot) prevents overwhelming upstream APIs
Two categories of providers fire in parallel:
Global Providers
These always fire regardless of the query. Specialist = "global":
| Provider Call | Source | Data |
|---|---|---|
getFearGreedIndex() | CoinGecko / CoinGlass | Market fear & greed index |
getGlobalData() | CoinGecko | Total market cap, BTC dominance, 24h volume |
getAltcoinSeason() | CoinGlass | Altcoin season index |
Per-Token Providers
These fire once for each token in the plan. For our query, just "BTC":
| Provider Call | Source | Data |
|---|---|---|
getTokenPrices(["BTC"]) | CoinGecko | Current price, 24h change, market cap, volume |
getOHLCV("BTC") | Binance | 4h candle data (OHLCV) for technical analysis |
getFullDerivativesData(["BTC"]) | CoinGlass | Open interest, funding rates, liquidations, long/short ratio |
getCoinDetail("BTC") | CoinGecko | Extended token info |
getTakerVolume(["BTC"]) | CoinGlass | Buy/sell taker volume ratio |
The technical specialist also triggers additional price + candle data providers.
Provider Resilience
Every single provider call passes through five layers of protection:
-
Health check —
isProviderHealthy(key)queries the circuit breaker. If a provider has failed recently, it's skipped entirely (no wasted time). -
Cache —
cacheGetOrCompute(key, fetchFn, TTL)checks the in-memory cache first. TTLs are domain-specific:Domain TTL Market data 60s Derivatives 45s Social 120s Macro 300s -
Retry —
withRetry(fn, { retries: 1 })with exponential backoff. One retry on failure. -
Concurrency limit — The global semaphore ensures no more than 30 API calls are in-flight simultaneously.
-
Settled — All providers run under
Promise.allSettled, so a single provider failure never kills the entire gather phase.
Results are assembled into a GatheredData object by the domain plugin's assembler — assembleCryptoTokenData() for crypto or assembleEquitiesData() for US equities. Each assembler normalizes provider-specific response formats into the unified structure consumed by the CoT pipeline.
5. Gap Detection + Supplementary Fetch
Files: src/brain/engine/gap-detector.ts, src/brain/engine/supplementary-fetch.ts, src/brain/engine/react-loop.ts
const gaps = detectGaps(data, plan, message);detectGaps() scans the gathered data for missing critical domains. For a BTC price query, the critical data (price + technicals) is almost certainly present. For our query, this step is skipped.
When gaps ARE found, the system has two escalation levels:
-
Supplementary fetch —
supplementaryFetch()does ONE round of retry: max 3 provider calls, 15-second timeout each. -
ReAct loop — If supplementary fetch still leaves critical gaps,
runReActLoop()runs an iterative Thought → Action → Observe cycle to find alternative data sources.
For "What's the price of BTC?" — data is sufficient. We proceed directly to the reasoning pipeline.
6. Chain-of-Thought Pipeline
File: src/brain/engine/cot/pipeline.ts
This is the reasoning core of the system. A critical design principle: Steps 1–4 are pure code with zero LLM calls (~0ms each). Step 5 is the ONLY LLM call in the entire request.
Step 0: Data Summary — buildDataSummary()
Formats raw gathered data into a human-readable context string for the LLM. If the summary exceeds 50K tokens, it's persisted to disk and a truncated preview is used instead.
Step 1: EXTRACT — extractFacts(data)
File: src/brain/engine/cot/extract.ts
Converts raw API data into structured Fact objects. For BTC, this typically produces 15–25 facts:
| Fact ID | Metric | Example Value | Importance |
|---|---|---|---|
price_BTC | Current price | $67,432 | 10 |
change_24h_BTC | 24h change | +2.3% | 8 |
rsi_14_BTC | RSI (14-period) | 62.4 | 7 |
volume_ratio_BTC | Volume vs 20d avg | 1.15x | 6 |
funding_avg_BTC | Avg funding rate | 0.012% | 7 |
oi_change_BTC | OI change (24h) | +3.1% | 6 |
ls_ratio_BTC | Long/short ratio | 1.23 | 5 |
fear_greed | Fear & greed index | 68 (Greed) | 5 |
btc_dominance | BTC market share | 54.2% | 4 |
Each fact carries: id, metric, value, formatted (human-readable string), domain, regime (bullish/bearish/neutral), and importance (1–10).
Facts are indexed into a FactTable with four access patterns: byId, byDomain, byToken, byRegime.
Step 2: TENSIONS — detectTensions(factTable)
File: src/brain/engine/cot/tensions.ts
Pure pattern matching that finds contradictions between facts. Example tensions for BTC:
- RSI approaching overbought (bearish signal) vs positive price momentum (bullish signal)
- High funding rate (crowded longs, bearish risk) vs strong volume (bullish conviction)
Tension rules are plugin-driven from each domain:
Crypto:
src/domains/crypto/tensions.ts— core tension rulessrc/domains/crypto/tensions-hl.ts— HyperLiquid-specific tensionssrc/domains/crypto/tensions-nansen.ts— Nansen on-chain tensions
US Equities:
src/domains/equities/tensions.ts— core equities tension rules (e.g., valuation vs momentum, insider selling vs bullish technicals)src/domains/equities/tensions-earnings.ts— earnings-specific tensionssrc/domains/equities/tensions-macro.ts— macro factor tensions (rates, yields vs growth)
Each tension includes: type, factIds (which facts conflict), strength (0–1), direction, and explanation.
Step 3: EVIDENCE CHAINS + RESOLVE
File: src/brain/engine/cot/resolve.ts
Two sub-steps:
buildEvidenceChains() — Constructs causal chains from facts: "X because Y because Z". Pre-defined chain templates include:
long_squeeze_setupaccumulation_phaserisk_off_cascademomentum_continuation
A key design rule: a chain of 3 aligned weak signals beats 1 strong signal.
resolve() — Weighs all chains and produces a final verdict:
{
direction: "BULLISH" | "BEARISH" | "NEUTRAL" | "NO_EDGE",
confidence: 0-100,
convergence: "strong" | "moderate" | "weak" | "conflicting",
support: number, // support level
resistance: number // resistance level
}For "What's the price of BTC?" — expect NEUTRAL or BULLISH with moderate confidence. It's a price query, not a directional trade question.
Steps 3.5–3.9: Enrichment Stages
All pure code, ~0ms each:
| Step | Name | Function |
|---|---|---|
| 3.5 | Gap Detection | Identifies data blind spots; injects caveats into the LLM prompt |
| 3.6 | Data Report Card | Grades data quality per domain (e.g., technical: A, social: C) |
| 3.7 | Regime Classification | Classifies current market regime: risk-on, risk-off, choppy, etc. |
| 3.8 | Multi-Agent Analysis | Runs parallel "analyst agents" in code (NOT LLM) — each scores from their domain perspective, then consensus voting determines overall direction |
| 3.9 | Alpha Factor Signals | Alpha engine generates factor-based signals from quantitative models |
Step 4: THESIS — buildThesis()
File: src/brain/engine/cot/thesis.ts
Assembles everything into a structured Thesis object — the complete blueprint the LLM will use to write prose:
{
direction: "NEUTRAL", // LOCKED — LLM cannot change this
confidence: 62, // LOCKED — LLM cannot change this
mustCiteFacts: [...], // facts the LLM MUST reference
leadChain: {...}, // primary evidence chain
supportChains: [...], // supporting evidence
counterChains: [...], // opposing evidence
tradeSetup: null, // only populated for trade_setup intent
regime: "risk-on", // market regime context
multiAgentContext: {...}, // analyst consensus
alphaSignalContext: {...}, // factor signals
episodicContext: [...] // previous similar analyses
}The mustCiteFacts array is the hallucination prevention mechanism — every fact listed here must appear in the final prose with a [F:id] reference.
Step 4.1: Episodic Memory
const episodes = await episodicStore.retrieve(query, tokens, 2);Searches for previous similar analyses. If BTC was analyzed recently with a different directional conclusion, that context is added to the thesis so the LLM can acknowledge the shift.
7. LLM Write — THE ONLY LLM CALL
File: src/brain/engine/cot/write.ts
const prose = await writeProse(thesis);This is the single LLM call in the entire request lifecycle. Everything before this was pure code.
Prompt Construction — buildProsePrompt()
The prompt is assembled from multiple sources:
| Component | Source |
|---|---|
| System prompt | Domain identity + synthesis rules from src/domains/{domain}/identity.ts (crypto or equities) |
| Thesis | Structured direction, confidence, must-cite facts with [F:id] references |
| Data summary | Raw numbers — protocol names, rankings, specific values |
| Report card | Data quality grades per domain |
| Multi-agent consensus | Which analyst agents agreed/disagreed |
| Alpha signals | Quantitative factor signals |
The LLM's Job
The LLM does one thing: write prose. It cannot:
- Change the direction (LOCKED in thesis)
- Change the confidence score (LOCKED in thesis)
- Invent numbers not present in the data
It must:
- Reference every fact in
mustCiteFacts - Produce coherent narrative from the structured blueprint
- Acknowledge tensions and counter-evidence
Model Selection + Fallback
Claude Opus 4 → GPT-5.4 → Claude Sonnet 4The primary model is Claude Opus 4. If it fails or times out, the system falls back through the chain. The Mastra Agent framework wraps the LLM call for structured output.
Output
writeProse() returns a ProseOutput:
{
clean: "Bitcoin is currently trading at $67,432...", // final prose
citedFacts: ["price_BTC", "rsi_14_BTC", ...], // which facts were referenced
uncitedNumbers: [], // numbers in text not traced to facts (hallucination risk)
verificationScore: 8 // 0-10 quality score
}The uncitedNumbers array is the hallucination detector — any number in the prose that can't be traced back to a fact gets flagged.
8. Post-Processing
File: src/brain/engine/cot/pipeline.ts
After the LLM returns, four background tasks run:
| Task | Function | Purpose |
|---|---|---|
| Auto-evaluate | autoEvaluate() | Checks prose quality, records lessons for future improvement |
| Episodic memory | episodicStore.save() | Saves this analysis so future queries can reference it |
| Reflection tracker | reflectionTracker.record() | Records the prediction for later accuracy checking |
| Model ELO | modelElo.update() | Tracks which model produced better quality over time |
These run asynchronously — they don't block the response.
9. Response Assembly
File: src/brain/router/brain.ts
Back in the brain router, final assembly happens:
-
Persist the assistant's message to the session:
await addMessage(sessionId, { role: "assistant", content: prose.clean }); -
Track synthesis cost (token usage for billing/monitoring)
-
Build the response object:
{
"session_id": "a1b2c3d4-...",
"content": "Bitcoin is currently trading at $67,432...",
"specialists_used": ["technical"],
"classification": {
"specialists": ["technical"],
"tokens": ["BTC"],
"intent": "price_analysis"
},
"correlation": {
"alignment": "NEUTRAL",
"score": 5,
"confirming": ["price momentum", "volume"],
"contradicting": ["funding rate"],
"sizing_multiplier": 1.0,
"summary": "..."
},
"latency_ms": 3500,
"timestamp": "2026-01-15T12:00:00.000Z"
}This JSON is sent back to the client. Total latency for a simple BTC price query: ~2–4 seconds, dominated almost entirely by the single LLM call.
10. SSE Streaming Variant
For requests with stream: true, the brain router uses the streamBrain() async generator instead of queryBrain(). The Hono route handler pipes each yielded event through streamSSE(), sending named SSE events with JSON payloads and incrementing IDs:
| Order | SSE Event | Data Payload |
|---|---|---|
| 1 | tool_call_started | { tool: "agent" } |
| 2 | tool_call_completed | { tool: "agent", latencyMs: N } |
| 3 | text_delta | { delta: "..." } — the full response content |
| 4 | done | { session_id, specialists_used, latency_ms, timestamp } |
| (err) | error | { session_id, error, latency_ms, timestamp } |
This means the client sees:
- Immediately: that the agent has started processing
- After 2–8s: agent processing complete with latency
- Next: the response text as a delta
- At the end: session metadata for programmatic use
Latency Breakdown
Where time actually goes for "What's the price of BTC?":
| Phase | Time | Why |
|---|---|---|
| Middleware + routing | < 5ms | Pure code |
| Classification | < 1ms | Keyword match — no LLM |
| Data gathering | 500–3000ms | Network calls to CoinGecko, Binance, CoinGlass (cached: < 10ms) |
| Gap detection | < 1ms | Simple data presence check |
| CoT Steps 1–4 | < 5ms | Pure code — extract, tensions, resolve, thesis |
| LLM write | 2000–8000ms | The bottleneck — single LLM call |
| Post-processing | < 5ms | Async, non-blocking |
| Total | 2500–11000ms | Typical: ~3500ms |
The single most impactful optimization target is the LLM call. Everything else combined is < 3 seconds even with cold caches.
Key Design Principles
-
One LLM call per request. The entire reasoning pipeline (extraction, tensions, evidence chains, resolution, thesis) runs in pure code. The LLM only writes prose from a locked blueprint.
-
Direction is computed, not generated. The LLM cannot decide if BTC is bullish or bearish. That decision is made by code in
resolve()based on weighted evidence chains. The LLM just explains the decision in natural language. -
Facts prevent hallucination. Every number in the response must trace back to a
Factextracted from real API data. ThemustCiteFactsmechanism anduncitedNumbersdetector enforce this. -
Fail gracefully.
Promise.allSettledin data gathering, circuit breakers on providers, model fallback chains, and gap detection with supplementary fetch — every layer has a degradation path. -
Cache aggressively, invalidate precisely. Domain-specific TTLs (45s–300s) balance freshness against provider rate limits. The semaphore prevents thundering herd problems.
-
Domain-agnostic core, domain-specific plugins. The CoT pipeline, correlation engine, and LLM write layer are shared across crypto and equities. Domain plugins provide keyword maps, data providers, tension rules, and identity prompts — making it straightforward to add new asset classes in the future.