Components — In / Process / Out
Every moving part of the firm as a clear input → process → output triplet, with the exact code location.
This page is the engineering reference: every component of HeliQuant — the LLM org and the LLM-gated floor — described as a clean In → Process → Out triplet with its file and function. It's deliberately terse; the narrative lives in Architecture, The Desks, and The Firm Machinery.
One honest frame for the whole page. The PM sign-off merge makes the LLM genuinely drive trades — but it creates no profit edge. The directional book is ~breakeven, and no edge has been validated on NEAR (the registry is empty).
How the two engines connect
The LLM Org (organization.py)
Steward
run_operations · organization.py · STEWARD_SYS
- In: deterministic whale-watchlist health report (
wm.evaluate(wm.load())). - Process: one LLM call judges the numbers →
MIGRATEorKEEP; on migrate,wm.migrate()re-scans GeckoTerminal. Falls back to a deterministic rule if the LLM is down. (Decides watchlist health only — the cycle's asset is chosen by rotation inapp.py, not here.) - Out:
{action, confidence, reason}+ before/after health + migration result.
The 10 LLM desks
build_desks · organization.py — each desk = (a real tool output) + (one LLM interpretation via
run_analysts, ANALYST_SYS). On NEAR AI Cloud every desk runs on Qwen/Qwen3.8-27B.
| Desk | Tool (In→Process→Out) | Code |
|---|---|---|
| Regime / Technical | features CSV → rule-based detect_current regime + ADX + dynamic R:R → {current_regime, adx, recommended_dynamic_rr, …}. XGBoost is the backtest engine, not the live call. | tool_regime |
| Macro (Allora) | Allora LCD read, keyless (BTC topic 14, ETH topic 9) → plausibility filter → {btc, eth, predicted_8h_usd, direction}; BTC-regime fallback if Allora is empty | tool_macro |
| On-chain / Risk | internal NEAR token-security check (wrap.near) + whale watchlist health + flow summary → divergence-vs-price → {token_security, whale_health, whale_flow, whale_divergence_vs_price} | tool_onchain_risk |
| Research | free public APIs (Fear&Greed, CoinGecko global/trending/prices) → {fear_greed_index, global_market, trending_coins, majors_24h_change_pct} | tool_research |
| Smart-Money Flow | firm/smart_money.py — POSITIONING mode (perp OI/funding/long-short) + Nansen macro netflow → {flow_score_0_100, read, macro_smart_money_nansen} | tool_smartmoney |
| Smart-Social | Elfa trending + per-asset mentions/news → {asset_in_top_trending, asset_attention_24h, top_narratives_24h} | tool_smartsocial |
| OI-Contrarian | validated_edges.json ∩ live OI-quintile signal → if edge_validated and actionable, a backtested reason to ENTER; else context-only | tool_oi_contrarian |
| Carry | scan perp funding annualized vs risk-free → {this_asset_carry, best_harvestable}; market-neutral yield, non-directional | tool_carry |
| NEAR Fundamentals | DeFiLlama NEAR chain TVL trend + 24h fees + staking yields → {near_tvl_usd, tvl_trend, ecosystem_risk} | tool_defillama |
| TimesFM Vol/Risk | daily realized-vol → next-day RV forecast (TimesFM 2.5 when configured, EWMA fallback) → {volatility{regime, sizing_multiplier}, direction (context-only)} | timesfm_desk.py |
Each desk's per-stance step:
- In: the tool output JSON + the desk's domain string.
- Process: one
ANALYST_SYSLLM call — interprets, never invents numbers. - Out:
{stance, confidence, key_point}.
Debate (Bull / Bear)
run_debate · organization.py · BULL_SYS / BEAR_SYS / *_REBUT_SYS
- In: all desk tool outputs + all desk stances.
- Process: 2 rounds (opening + rebuttal), 4 deep-model LLM calls — surfaces dissent before the PM.
- Out:
{bull, bear, bull_rebuttal, bear_rebuttal}.
Portfolio Manager
run_pm · organization.py · PM_SYS
- In: desk stances ranked by learned reliability (
_ranked_desk_view) + the debate + regime status + advisory briefs (memory, carry, flow-intel, whale, NEAR fundamentals — all additive, never altering the gates). - Process: one deep LLM call. Rule: a pure trend thesis → ABSTAIN; the one ENTER exception is a validated, actionable OI-Contrarian edge; a hard rugpull veto forces ABSTAIN.
- Out:
{decision, direction, confidence, reasoning, desk_consensus, self_management}.
finalize_decision
organization.py
- In: the PM decision + desks + real structure (entry/ATR/swings via
_state,_swings). - Process: on ENTER, builds a gated
trade_ticket; if it fails the R:R gate, re-prompts the PM up to 2× (MAX_TICKET_REPAIR), then overrides to a disciplined ABSTAIN. Never repairs up to a trade. - Out: the decision with
trade_ticket+ticket_noteattached (or ABSTAIN).
trade_ticket
trade_ticket.py — build_trade_ticket → build_levels + size_position + validate_ticket
- In: direction + conviction (from the PM) + real ATR/swing structure + optional
edgeprofile. - Process: price math for entry zone / structural stop / TP ladder / R:R;
size_positionpicks SAFE (conviction band 0.5–1.5%) or AGGRESSIVE (fractional Kelly —kelly_fraction_staris its output field), clamped to ≤ 3% risk / ≤ 5× leverage with a 20% drawdown breaker; crowding sizes down only. Then the Layer-3 gate validates R:R ≥ 2, consistent levels, caps, allowlist. - Out: a
{valid, problems, entry_range, stop_loss, take_profit[], mode, risk_pct, notional_usd, kelly_fraction_star, …}ticket.
Deterministic / real-source tools
The numbers the desks interpret are computed here (no LLM):
| Tool | In → Process → Out | Code |
|---|---|---|
tool_regime | features CSV → detect_current rules + ADX → regime + dynamic R:R | organization.py |
tool_onchain_risk | internal NEAR token check + whale watchlist → security + flow + divergence | organization.py |
tool_smartmoney | firm/smart_money.py (POSITIONING) + Nansen → flow score + read | organization.py |
tool_macro (Allora) | allora_client BTC/ETH 8h prediction → direction + predicted price | organization.py |
whale_manager | watchlist scoring + migrate() re-scans GeckoTerminal for Rhea pools | whale_manager.py |
| DeFiLlama | keyless NEAR TVL/fees/staking → ecosystem risk-on/off brief | defillama_client.py |
| NEAR screen | internal token-security check (holders, liquidity, honeypot reported unverified) for NEAR assets | via sources/rugpull in tool_onchain_risk |
| Elfa | trending mindshare + per-asset social attention | elfa_client.py |
| Nansen | funds' real ETH netflow (macro smart-money, credit-frugal) | nansen_client.py |
Non-desk roles
| Role | In → Process → Out | Code |
|---|---|---|
desk_performance | stance of the 9 directional voices vs realized direction → reliability weight 0.6–1.4 (≥15 samples, else neutral) → advisory prior to the PM | desk_performance.py |
edge_lab | a hypothesis library × asset history → cost-aware OOS + 5-fold walk-forward + outlier-robust + BH-FDR → validated / candidate / rejected | edge_lab.py |
exploration | on ABSTAIN, flow-consensus reads → a paper trial → resolved at 24h → a learned lesson (never repeated) | exploration.py |
macro_calendar | clock → is now inside a FOMC/CPI window? → de-risk flag | macro_calendar.py |
onchain_recorder | a decision → canonical record + SHA-256 → core.anchor signed by the executor key | onchain_recorder.py |
agent_onchain | each desk's output + jobId → core.record_output per desk, signed by that desk's own limited key | agent_onchain.py |
state_store | key/value → Supabase hq_state (local-JSON fallback) → survives Railway redeploys | state_store.py |
memory_store | a decision + later its outcome → SQLite / Supabase decisions_hq → recall() past trades for the PM | memory_store.py |
The Floor (now LLM-gated) (campaign.py)
A continuous paper trader at live prices (real Bitget Demo fills only when BITGET_EXECUTE=1).
Signals (the floor's own conviction — no LLM)
desk_votes · campaign.py — sums a directional vote:
- flow-intel stance (
flow_intel.synthesize) + z-score positioning extremes (OI/funding/flow/momentum) fromdata/<asset>_positioning.csv(fed throughPOST /ingest); - Hyperliquid whale read, double-weighted when high-conviction (
hl_whales.whale_read); - NEAR-TVL lean for NEAR-ecosystem assets (
_near_lean, DeFiLlama), gated by price confluence. - In: the positioning CSV (used only when ≤ 12h old) + live whale/TVL. Out:
(net_votes, reasons[]).
Live tools (cheap, deterministic)
| Tool | In → Process → Out | Code |
|---|---|---|
_trend | 1h klines → price vs SMA24 + slope → up/down/flat (the responsive regime proxy) | campaign.py |
_atr_pct | 1h klines → ATR(14)/price → per-asset volatility for SL/TP sizing | campaign.py |
_range_pos | last 24×1h high/low → 0..1 position in range (mid-range = chop) | campaign.py |
_extension | 20-bar mean → signed ATRs stretched + decel flag (don't chase the tail) | campaign.py |
tv_ta | TradingView 1h vs 1D consensus → abstain / fade / ok | tv_ta.py |
_whale_conviction | HL whale stance + is-high-conviction → veto a trade whales oppose | campaign.py |
The entry-gate pipeline
step · campaign.py. An ordered, per-asset stack (each is a plain skip — abstaining one asset
never stalls the basket). The live list is on /campaign as entry_gates:
- macro event-risk de-risk (
macro_calendar) · 2. deep-cold bench · 3. cold-cadence throttle · - mid-range chop · 5. clear-trend required (flat → abstain) · 6. don't-fight-trend flip (contrarian → trend-follow) · 7. TV 1h-vs-1D counter-daily · 8. smart-money whale veto · 9. over-extension ·
- fee-breakeven near-TP guard (exit-side) — then the new final gate:
PM sign-off (the merge — final gate)
pm_signoff.signoff · pm_signoff.py · called from campaign.py · step
- In: the floor's candidate (asset, direction, top reasons) + live signals
{trend_1h, stretch_atr, tv_vs_1d, range_pos, whale, size_usd, sl_pct, tp_pct}— fresh, not the org's CSVs. - Process: one LLM call (
SIGNOFF_SYS;z-ai/glm-5.3-flashon NEAR AI Cloud, Groq whenHQ_PROVIDERis notnearai) → APPROVE / VETO. Fails open (approve) on any error (pm_signoff.py) so a 429/outage never freezes the floor. TogglePM_SIGNOFF(default on). - Out:
{approve, reason, model}— recorded on the position asp["pm"](campaign.py); a VETO logs a shadow for later scoring.
Sizing
Inline in step (campaign.py):
- In: vote tier (
STRONG≥2 votes →$100, elseLEAN→$50), heat, per-asset record. - Process: anti-martingale heat concurrency (
_heat_slots); warm/cold ladder (_asset_perf→ cold = ½ size + 1-of-3 cadence; warm = ×1.3, strong = ×1.6, capped below the ×2 reserved for a validated edge);cond_recordlearned fade (½ on a proven-losing condition@regime). - Out: the dollar
size_usdfor the position.
Stops & exits
- Calibrated TP/SL (
_tp_sl_mult) — per-asset ATR multipliers measured from realized excursions (MFE/MAE; the fixed 2.5× TP was reached only 0–21% of the time). Fallback 2.5×/1.8× ATR. - Trailing (
campaign.py) — trend-follow/edge trades ratchet a chandelier stop toward price. - near-TP fee-guard (
NEARTP,campaign.py) — locks an ≥80%-to-TP gain only if it clears the round-trip cost (a sub-fee "win" is never booked). - STALL (
campaign.py) — a non-edge trade not following through (gross < 0.3%) by 2h is cut. - TIME (
campaign.py) — the dynamic horizon cap (_dynamic_horizon): 3h fade / 4h trend / 24h validated edge. - In: live mark + the position. Out: an exit reason
∈ {TP, SL, TRAIL, NEARTP, STALL, TIME}+ net PnL (net of 20 bps round-trip).
Execution
_exec_open / _exec_close · campaign.py
- In: an approved position + the
BITGET_EXECUTEflag. - Process: LONG / SHORT on Bitget demo futures (
BITGET_EXECUTE=1,bitget_adapter.py, API v3). Orders go to the Bitget Demo account:bitget_adaptersends thepaptradingheader whileBITGET_DEMO=1(the default). Paper is the source of truth; demo fills are proof-of-execution. - Out:
venue+exec_qtyon the position (or paper-only if geo-blocked / disabled).
Learning (floor side)
cond_record(campaign.py) — every close updates a(condition@regime)record that steers future sizing; a losing round benches its conditions with a TTL (failed_conditions)._asset_perf(campaign.py) — per-asset realized record drives the warm/cold ladder + bench.- shadow-score (
campaign.py) — each abstained setup is logged and judged at its horizon against real price: was the gate right (would-be loss) or wrong (would-be win)? Surfaced asshadow_learning. tp_sl_calibration(tp_calibration.py,data/tp_sl_calibration.json) — re-measures reachable TP/SL from accumulated trades.
See also
- Architecture — the 3-phase loop + the entry-quality pipeline visualised.
- The Firm Machinery — the merge and the non-desk roles in prose.
- The Desks — each desk's own deep-dive page.
- API Reference — where each component's output surfaces as an endpoint.