Repository: https://github.com/qrak/LLM_trader.git Python: 3.13,
.venv/,python start.pyExecution: with[executor_api] enabled = truedecisions are forwarded to a separate executor service (not in this repository); withenabled = falsethe book is simulated Live Dashboard: https://semanticsignal.qrak.org
Root AGENTS.md is the single instruction source of truth in this repository across all IDEs, agents, and harnesses.
- Root
AGENTS.mdis canonical for system-wide rules, architecture, coding standards, testing, terminal behavior, and governance. - IDE-specific instruction files are non-authoritative and should not contain policy that is missing from
AGENTS.md. .github/workflows/*defines CI execution behavior, not instruction authority.
Asyncio-first trading bot: market data, news (RAG) and chart images become structured BUY / SELL / HOLD decisions from an LLM. A central trading loop coordinates data ingestion, technical analysis (Numba indicator kernels), RAG retrieval, risk validation, an outcome-aware brain (vector memory + reflection), and an order-governance chain. Filled orders are executed by a separate service; the bot keeps the decision loop and books what the venue actually did.
DataFetcher ─▶ AnalysisEngine ─▶ ProviderOrchestrator ─▶ UnifiedParser
(CCXT) TechCalc+Pattern+Chart+RAG+Brain (fallback chain)
│
BrainContextProvider ◀── vector memory ◀── closed trade ▼
(confidence + rules into next prompt) GuardPipeline ─▶ RiskManager
│ (SL/TP, size)
▼ │
TradingStrategy ◀─────────┘
(R:R gate, OrderLifecycle, ExitMonitor)
│
executor_api ─▶ venue, verdict journal ─▶ booking
| # | Agent Name | Primary Responsibility | Core Model | Core Implementation |
|---|---|---|---|---|
| 1 | 🧠 Brain Agent (TradingBrainService) | Outcome-aware decision enricher, semantic rule learning via reflection loops, confidence calibration | Deterministic/vector memory; context is injected into provider-routed LLM prompts | src/trading/brain.py |
| 2 | 🔬 Analysis Engine Agent | Market data collection, 50+ technical indicators, pattern recognition, chart generation, AI signal synthesis | Provider-routed (provider in config/config.ini); the chart-vision step needs a multimodal model |
src/analyzer/analysis_engine.py |
| 3 | 📰 RAG Engine Agent | News aggregation (RSS + full-article enrichment), fundamentals (DeFiLlama), relevance scoring, context retrieval | Deterministic (no LLM) | src/rag/rag_engine.py |
| 4 | ⚙️ Risk Manager Agent | Dynamic SL/TP scaling, position sizing, signal validation, circuit breakers | Deterministic | src/managers/risk_manager.py |
| 5 | ☁️ Provider Orchestrator | AI provider lifecycle, multi-provider fallback chain, parameter negotiation | — | src/managers/provider_orchestrator.py |
| 6 | 🛡️ Governance Pipeline | Pre-execution guard chain: symbol whitelist, max position size | Deterministic | src/trading/guards/pipeline.py |
| 7 | 📊 Dashboard Agent | Real-time FastAPI + WebSocket monitoring, performance analytics, brain state inspection | — | src/dashboard/server.py |
start.py → SingleInstanceLock → Event loop with GracefulShutdownManager → 9-stage dependency provisioning (src/composition/provisioners.py):
| Stage | Provisioner | Dependencies Created |
|---|---|---|
| 1 | _provision_infrastructure |
ExchangeManager, aiohttp session, KeyboardHandler |
| 2 | _provision_utilities |
FormatUtils, UnifiedParser, TokenCounter, PromptBudgetPolicy, TimeframeValidator, CategoryCollisionResolver |
| 3 | _provision_platforms |
CCXTMarketAPI, CoinGecko, Alternative.me, DeFiLlama, RSS news client + article-body enricher |
| 4 | _provision_rag_layer |
RagEngine, NewsManager, LocalTaxonomyProvider, TickerManager |
| 5 | _provision_model_layer |
AI provider clients, ProviderOrchestrator, ModelManager |
| 6 | _provision_analyzer_layer |
AnalysisEngine, MarketDataCollector, TechnicalCalculator, PatternAnalyzer |
| 7 | _provision_trading_layer |
TradingStrategy, ExitMonitor, VectorMemoryService, TradingStatisticsService, TradingBrainService |
| 8 | _provision_notifiers |
Discord notifier with file handler, or console fallback notifier |
| 9 | _provision_dashboard_layer |
DashboardServer, DashboardState, force_analysis_event |
Architectural invariant: All services are instantiated in the composition layer and injected via constructor parameters. Never construct service dependencies inside other service classes, and never use in-function lazy imports (Pylint C0415) to resolve circular dependency cycles — refactor constructor parameter injection at the CompositionRoot (start.py) instead.
AnalysisEngine.analyze_market()
├── MarketDataCollector → DataFetcher (OHLCV + order book + trade flow)
├── TechnicalCalculator (50+ indicators) + LongTerm data + Weekly macro
├── PatternAnalyzer → IndicatorPatternEngine (deterministic indicator-pattern kernels)
├── ChartGenerator (1920×1080 PNG) → LLM visual chart-pattern analysis (analysis_result_processor.py)
├── RAG context retrieval
├── Brain context injection (confidence + rules similar to current conditions)
├── AI provider call → TradingAnalysisResponseModel (prompt step 5.5: the model must
│ name a specific invalidation trigger or HOLD)
└── Structured dict returned to TradingStrategy
↓
TradingStrategy.process_analysis()
├── PositionExtractor + UnifiedParser → extract and validate signal
├── GuardPipeline (symbol → max size)
├── RiskManager → RiskAssessment (SL/TP scaling, computes R:R)
├── R:R gate: max(config `min_rr_entry`, brain floor) — both 0.0 by default,
│ so the gate is inert unless a floor is configured or learned
├── OrderLifecycle → INTENT → READY_FOR_REVIEW (or REJECTED); execution proof is
│ owned by the position-intent ledger, so there is no EXECUTED order state
├── CycleCheckpointStore → one terminal cycle state per analysis (analyzing is in memory)
│ see `docs/STATE_MACHINES.md`
├── executor_api forward (order_id keyed) when `[executor_api] enabled = true`
├── PersistenceManager → SQLite-only trade_history.db append (no JSON fallback)
├── RiskManager friction drain → store_blocked_trade feedback for brain learning
└── ExitMonitor (soft at candle close; hard at a configurable interval per SL/TP type)
└── PositionStatusMonitor → background asyncio loop with dynamic rescheduling
↓
BrainAgent.update_from_closed_trade()
├── BrainExperienceRecorder → store vector memory
├── trade_count++ → schedule reflection if interval reached
└── ReflectionEngine → sequential: best-practice → anti-pattern → AI-mistake rules
Per cycle the bot snapshots CostStorage before and after the LLM work (chart, text,
contract retry and any awaited post-mortem) and appends the delta to
data/trading/metrics/cycles.jsonl. The last 20 measured costs feed the EV framework,
whose 1.5× threshold covers the round-trip fee plus inference cost; with no measured
cost the EV prompt stays fee-only.
GracefulShutdownManager: SIGINT/SIGTERM → drain active analysis → persist state → close providers → flush logs; the keyboard handler performs a manual stop with state preservation.
Closed trade ─▶ BrainExperienceRecorder ─▶ ChromaDB (vector memory)
├── update matched semantic-rule validation / contradiction counters
├── trade_count % interval == 0 → ReflectionEngine
│ (best-practice → anti-pattern → AI-mistake rules)
└── next cycle: BrainContextProvider queries ChromaDB for
similar past trades (top-3, latest 20 for the win rate),
rules ranked by similarity + evidence + timeframe freshness,
confidence stats by level, blocked-trade feedback → injected
into the LLM prompt
Semantic-rule policy:
- Active semantic rules are durable learned policy and are not deleted by age-only pruning; they are deactivated by evidence. Inactive old rules may be pruned as storage maintenance.
- Rule influence is soft-ranked by semantic similarity (55%), evidence quality (25%), timeframe-aware freshness (15%) minus a contradiction penalty (5%). Recency is therefore part of the ranking, not a filter.
- Closed trades whose direction, regime, ADX bucket and confidence match a rule's declared condition update validation or contradiction metadata used by that ranking. A rule that describes a losing pattern (
anti_pattern,ai_mistake,corrective) is validated by a loss and contradicted by a win. - A rule declares the direction, regime and ADX bucket it was learned under. Rules stored before that was written into metadata are read with the conditions recovered from
source_pattern, anchored on the firstLONG/SHORTtoken: a legacysideways_failure|MEDIUM|LONG|BULLISH|…parses, and a pattern with no direction token stays global. Nothing is migrated and nothing is re-indexed. - The prompt prints that scope in front of the rule text, lists rules whose declared regime and ADX bucket match the snapshot first, and prefixes a mismatched rule with
scope mismatch. The direction of the next decision is unknown when the prompt is built, so a rule is scoped and ranked, never dropped. - Re-synthesising a rule under the same id keeps its accumulated counters, its first-seen timestamp and its retirement state.
- Retirement happens on the reflection interval: three contradictions, at least half the rule's stored support and more contradictions than validations set
active=falsewith anauto: …reason. A retired id keeps its retirement state when re-synthesised, so it only comes back throughpython scripts/brain_rules.py reactivate --id <rule>. - Every prompt build logs one
Brain recall:line (closed trades, active rules, served rules, scope matches, blocked feedback, trade journal, estimated brain tokens), so the injected context is auditable without re-reading the whole prompt. - Surprise ratio (
|realized P&L - expected P&L| / max(|expected P&L|, 0.01), the expectation being the take-profit distance) is computed at trade close. A high ratio (>1.5) means the outcome came from factors outside the entry thesis — the trade won despite flawed reasoning (or lost despite good reasoning). Each synthesised rule carries its average surprise in the text; a best-practice rule above 1.5 also carries the⚠️ high surpriseannotation so the LLM can discount lucky outcomes.
- Trade history is SQLite-only at
data/trading/trade_history.dbviaSQLiteTradeHistoryandPersistenceManager. - Runtime code must not read, write, or auto-migrate
trade_history.json; historical.json.migratedfiles are backups, not runtime inputs. PersistenceManager.save_trade_decision()fails loudly if SQLite persistence fails — do not add JSON fallback paths.- Dashboard, brain entry-decision lookup, and query scripts consume trade history through injected persistence or SQLite APIs.
- Zero Backward Compatibility & Startup Clutter Policy:
- Runtime code in
src/andstart.pystays canonical and clutter-free. - Never introduce inline schema migration
ALTER TABLEstatements, legacy unit conversion methods, rule migration hooks (refresh_semantic_rules_if_stale), ortry/exceptfallback paths into runtime service initialization. - Never add
sys.path.insert(0, ...)manipulation hacks tostart.py, and never add startup auto-rehydration loops there. Database or vector-storage rehydrations run as standalone CLI scripts inscripts/, executed once and deleted. - Classes Only in
src/utils/: every utility concern is encapsulated as a class (TokenCounter,PromptBudgetPolicy,PeakRates); standalone utility functions are forbidden.
- Runtime code in
Operator's local config/config.ini (gitignored; the tracked template is config/config.ini.example). These are the values of one deployment, not defaults. Key settings:
| Setting | Value |
|---|---|
| Pair | BTC/USDC |
| Timeframe | 4h |
| Candles | 999 (125 for the AI chart) |
| Capital | $10,000 simulated (demo_quote_capital) |
| Fee | 0.075% (transaction_fee_percent) |
| Inference cost | CostStorage delta per cycle; rolling 20-analysis average in the EV prompt; no config key |
| Max Position | 10% of portfolio (max_position_size) |
| Fallback sizes | 1% / 2% / 3% (LOW/MEDIUM/HIGH confidence) |
| R:R entry floor | min_rr_entry = 0.0 (gate inert until set) |
| News update | Every 4 hours, 5 articles max |
| Provider | provider = commandcode in the operator config, commandcode_model = deepseek/deepseek-v4.1-flash on the Command Code Provider API; opencode_model = deepseek-v4.1-flash on the Go endpoint stays configured as the rollback; the tracked example defaults to provider = googleai; DeepSeek deepseek_model = deepseek-flash; OpenRouter base google/gemini-3-flash-preview, fallback deepseek/deepseek-v4.1-flash |
| Executor | [executor_api] enabled = true, url = http://127.0.0.1:9199/decision |
| Market data source | [exchanges] sandbox = false → real exchange book; true → testnet book |
| Timezone | [general] timezone = Europe/Warsaw — human-readable timestamps only (logs, notifications, check headers, chart labels); trading stays on UTC candles |
| Real-market stop | [risk_management] reference_exit_check_seconds = 10 (0 = off; pairs with the executor's PROTECTION_BACKSTOP_MULTIPLIER) |
| Dashboard | 0.0.0.0:8000 |
timeframelives in[general]and is read only throughConfig.TIMEFRAME/Config.TIMEFRAME_MINUTES. A literal ("4h",240) anywhere outsideTimeframeValidatorand theDataFetchermacro constants is a defect, not a shortcut.- Prompt text is a consumer too.
build_system_prompt()andbuild_response_template()must renderConfig.TIMEFRAME; a frame embedded in a longer sentence is still a literal, and the AST gate only matches a whole string constant. The render test intests/domain_infra/test_config_propagation.pyis the gate for prompt prose. - A consumer never carries its own default for a configured value. The default lives in the loader or nowhere; a missing required key aborts startup naming the file and the key (
Config.REQUIRED_CONFIG_KEYS). - Prompt prose renders what the runtime enforces, not a parallel table. The position caps come from
RegimeRiskProfileSelector.effective_caps(MAX_POSITION_SIZE)and the decision thresholds fromsrc/trading/threshold_defaults.py; a hardcoded10%or a second.get(key, default)is the same defect as a hardcoded4h. A value the prompt cannot resolve is an error, never a plausible substitute. - Every config key is
restart-scoped:Configis read once at import and services bind their frame/dependencies at startup. Nothing may advertisehot/cycleapplication until a real reload exists, and an in-app editor must not promise it either. The local settings desk writesconfig.ini/keys.envfor the next start, validates the candidate withConfig(config_path=...), and never claims a running process picked it up. - A new config key ships in the same change as
config/config.ini.example,Config.REQUIRED_CONFIG_KEYS(when the runtime cannot work without it),docs/CONFIGURATION.md, and the contract test. - The effective values are logged once at startup (
Effective configuration: ...). That line is the runtime evidence that the ini reached the process, so quote it instead of assuming.
LLM_trader/
├── start.py # Entry point + CompositionRoot + SingleInstanceLock
├── AGENTS.md # THIS FILE — master rules; package detail lives in src/*/AGENTS.md
├── README.md / CHANGELOG.md # Overview & setup / version history (newest first)
├── docs/ # changelog-archive-{2025,2026}.md, FEATURES/SETUP/CONFIGURATION, assets/
├── requirements.txt / -dev.txt / -mcp.txt / constraints.txt
├── keys.env / keys.env.example # Secrets (gitignored / template)
├── config/
│ ├── config.ini # Active configuration
│ ├── model_pricing.json # Per-model cost data (BASE rates)
│ ├── peak_rates.example.json # Optional peak/off-peak billing windows
│ └── rag_priorities.json # RAG priorities (important_categories + generic_priorities)
├── src/
│ ├── app.py # Main application wiring (ApplicationServices)
│ ├── composition/ # provisioners.py, startup_support.py — DI wiring
│ ├── trading/ # 🧠 Brain + Strategy + Monitors
│ │ ├── brain.py # TradingBrainService (facade) + brain_*.py collaborators
│ │ ├── trading_strategy.py # Strategy orchestration
│ │ ├── exit_monitor.py # Hard/soft exit checks
│ │ ├── vector_memory.py # ChromaDB interface + vector_memory_*.py collaborators
│ │ ├── executor_reconciliation.py # tri-state position truth + intent journal
│ │ ├── regime_risk_profile.py # Regime-aware risk profile (Risk Manager)
│ │ ├── statistics.py # P&L tracking
│ │ └── guards/ # 🛡️ Governance Pipeline (2 guards + pipeline.py)
│ ├── analyzer/ # 🔬 Analysis Engine (analysis_engine, technical_calculator,
│ │ # pattern_engine/, prompts/, formatters/, data_fetcher)
│ ├── rag/ # 📰 RAG Engine (rag_engine, news_manager, news_ingestion/)
│ ├── managers/ # ⚙️ Risk Manager, persistence_manager, sqlite_trade_history,
│ │ # provider_orchestrator, model_manager
│ ├── dashboard/ # 📊 server.py + routers/ (5 REST routers + console + ws_router)
│ ├── indicators/ # 65 Numba-compiled indicator functions
│ ├── platforms/ # AI provider clients + exchange APIs
│ ├── parsing/ # UnifiedParser
│ ├── logger/ # Structured logging
│ ├── mcp_tools/ # MCP history server (read-only trade-history queries)
│ ├── notifiers/ # Discord, console, file handler
│ └── utils/ # Profiler, token counter, decorators, time_utils (classes only)
├── tests/ # test_*.py in domain_{trading,brain,rag_indicators,infra}
│ # + conftest.py
├── data/ # Runtime state (not committed)
├── logs/Bot/YYYY_MM_DD/ # Bot.log (all levels) + errors.log (error level)
└── scripts/ # Cross-platform startup scripts (Windows .ps1 are gitignored)
- Exchanges: Binance, KuCoin, MEXC, Hyperliquid via CCXT (
gateiois not a valid CCXT id — the ccxt name isgate, so that entry never loads) - Market Data: CoinGecko, Alternative.me, DeFiLlama, CCXT exchange market data
- AI Providers: Command Code (active
provider, GOAT subscription, OpenAI-compatible), OpenCode Go (subscription, OpenAI-compatible), DeepSeek, OpenRouter (base + fallback models), Google AI and LM Studio as configurable providers; BlockRun participates only in theallchain - Decision gate: OpenRouter's alpha Decisions endpoint (
/api/alpha/decisions,openai/gpt-6-luna-decisions) over the sameOPENROUTER_API_KEY; it scores a decision and may only shrink the size ([decisions_gate] mode = off|shadow|size), never veto an entry - Execution: external
llm_trader_executorservice over HTTP (127.0.0.1:9199), which places real exchange orders via CCXT and writes the verdict/exit journals the bot reads - News Sources: CoinDesk, CoinTelegraph, Decrypt, CryptoSlate RSS feeds, with full-article page enrichment over plain HTTP (
src/rag/news_ingestion/article_body_enricher.py)
- Send one terminal command per tool call.
- Never include control-key text in commands (for example
^U,^C,^[). - On Windows/PowerShell in VS Code, prompt-edit control text such as
^Uis sent literally and becomes part of the command name. Do not assume Linux/readline behavior. - Never send terminal follow-up probes or marker echoes (for example
Write-Output $LASTEXITCODE,echo DONE, or a "flush" command) to recover hidden or truncated validation output. - If validation output is incomplete, either trust the user's visible terminal output when provided or rerun the exact validation command once with a generous timeout.
- Never chain validation commands with
;,&&, variable assignment, redirect/capture, and readback in one line. - For pytest validation, trust only raw output from a direct pytest command.
- If terminal output is empty or malformed, do not claim success, and never infer pass/fail from a trailing exit-code marker.
Keep platform-specific setup, startup, test, lint, and type-check commands in README.md. This file documents agent architecture and execution policy only.
- Execution is delegated: with
[executor_api] enabled = truethe bot forwards intents to the separate executor service, which places them on the venue (testnet or real, per its own config); withenabled = falsethe bot books a simulated book only. Check the config value before describing the mode. - Hard SL/TP exits run at 15-minute intervals; soft candle-close exits are supported by
ExitMonitor. - Max position: 10% of portfolio; simulated capital: $10,000 with a 0.075% fee model.
- Fail-closed behavior if governance/risk validation cannot decide safely.
Use this checklist for every documentation or tooling-policy PR:
- All behavioral policy changes are documented in root
AGENTS.md. - Do not introduce IDE-specific policy files (Copilot, Claude, Windsurf instruction docs) as authoritative guidance.
.github/workflows/*may define CI execution logic only; workflow comments must not replace policy documentation inAGENTS.md.- If a command, validation rule, or safety guard changes, update the related AGENTS section in the same PR.
- Before merge, search the repository for stale references to removed tool-specific instruction files.
- A new mechanical rule ships with its row in §12.1 and a test that fails when the gate is removed.
Any new tool-specific instruction file must be a non-authoritative pointer to AGENTS.md; if it contains independent policy, reject it in review.
README.md is the landing page; the long-form pages live in docs/ so the README stays
scannable. A fact belongs in exactly one of them and is linked from the others, never copied.
| File | Scope |
|---|---|
README.md |
What the project is, how it performs, how it compares, quick start |
AGENTS.md + package files |
Policy, architecture, conventions, verification gates |
docs/FEATURES.md |
Every feature in detail, with the implementing file |
docs/STATE_MACHINES.md |
Every stored or derived lifecycle, its evidence and its user/API surface |
docs/SETUP.md |
Requirements, platform scripts, secrets, where the website lives now |
docs/CONFIGURATION.md |
Every config key, prompt budget, billing windows, executor handoff |
docs/README.md |
Documentation index; the reader's entry point |
docs/SETTINGS_PANEL.md |
Local settings desk: access, tabs, validation, restart, troubleshooting |
CHANGELOG.md |
Dated changes with the run that verified them |
python scripts/check_agents_md.py fails when a path quoted in an AGENTS file or in the
reader-facing docs (README.md, CONTRIBUTING.md, docs/*.md) no longer exists — run it after any
rename, and CI runs it on every push.
No comments. No docstrings. A # comment in Python or a // comment in JS/CSS/HTML is deleted on sight; only machine directives survive (# noqa, # type: ignore, # pylint:, # pragma:, /* eslint-disable */). No module, class, function or method carries a docstring, and no bare string statement stands in for one — names, signatures and types must explain the code. Reasoning belongs in the commit message, the change description, the package AGENTS.md or this file. python scripts/check_comment_policy.py fails the build otherwise.
- Dependency injection only. Every class receives its dependencies (
logger,config, collaborators) through__init__; the single composition root isstart.py. Never construct a collaborator inside a method. self.logger, neverself._logger—@retry_asyncreadsinstance.logger.- No standalone functions in
src/app.py, and no loose helper modules: every concern is a class wired once fromstart.py. Utility code lives insrc/utils/as classes. - Top-level imports only. An in-function import added to dodge a circular import means the wiring is wrong — fix it in the composition root.
- No
sys.pathmanipulation and no startup auto-rehydration loops instart.py; one-off data conversions run as a script that is executed once and deleted.
- A private helper used by one class lives in that class. If
_nameis referenced only from the body of a single class in the same module, it is a@staticmethod/@classmethodof that class — never a loosedefbeside it.python scripts/check_loose_helpers.pyfails the gate otherwise (andtests/domain_infra/test_loose_helpers.pyruns the same check in the suite); itsALLOWLISTcarries any accepted exception with its reason. - A new family of helpers is a class, not a module of functions. Behaviour with state (a path, a client, a pair of strategies) is a class instantiated once from
start.py; a stateless family is one class with@staticmethods —NewsBoilerplateCleaner,ArticleBodyTextExtractor,ExitRecords,TradeHistoryReader. - A free function survives only for one of these reasons, named in the package
AGENTS.mdor the change description: a decorator factory (retry_async,retry_api_call), anumbakernel (@njitcannot compile a method), a framework entry point that must be free (MCP tool registration, FastAPI route handlers,main()), or a pure function shared by two or more classes. - No free function sits between two class definitions. Order in a module: constants, helper functions, classes, module API. A
defbetween twoclassstatements means a helper was never absorbed.
- Types are known, so do not probe them. A signature, a dataclass or a protocol already states the shape: read attributes and call methods directly.
getattr/hasattr/isinstanceon a value whose type the annotation states is a defect — it turns a broken contract into a silent default and hides the crash that would have named the caller.TradeDecisionandPositionare@dataclass(slots=True)with fixed fields: neverhasattr/getattr/isinstanceon them. - A guard is legitimate only where the type genuinely cannot be known: raw LLM/API/JSON payloads (
dict | None), third-party SDK objects typedAny, exception classification, a declaredX | Yunion, and the interpreter'ssys.frozen. The annotation says so (Any,dict | None,X | Y), so the next reader knows why. Tests andscripts/are exempt. - The strategy's public surface is a contract, not a probe target: call
position_snapshot_token(),protection_snapshot(),protection_loosening_reason(),reconcile_local_position(),resolve_position_intents_after_forward()and the one-shottake_*()readers directly. Wiring a double means implementing the method, not making the caller duck-type it. - Every timestamp printed for a human goes through
src/utils/time_utils.py:utc_stamp()for UTC-only text,utc_and_local()for a paired label,local_stamp()/day_stamp()for log lines and folders. Trading arithmetic, persistence and TTLs stay on UTC epoch or aware UTC datetimes — never on the wall clock. - Raw payloads from LLM output or API responses are
dict | None: read them with.get(). TradeDecisioncarries noorder_type/reduce_only; those come fromENTRY_ORDER_TYPEandanalysis.get("reduce_only", False).- Validate numbers at the boundary: NaN/Inf are rejected where they enter (
_parse_finite_number,math.isfinitefor timestamps), andserialize_for_jsonmaps NaN/Inf toNone. SerializableMixin.from_dict(to_dict(obj))must round-trip nested tuples and datetimes.
- Narrow exception handling. A bare
except:never exists; a broadexcept Exceptionis a deliberate fail-open or fail-closed decision that the packageAGENTS.mdor the change description explains. Never fix a bug by catching and ignoring. - Every queue eviction is logged with context; every
asyncio.gatherhandles per-task exceptions explicitly instead of swallowing them. - No hand-rolled retry loops:
@retry_async(src/utils/decorators.py) for network and exchange calls,@retry_api_callfor AI provider calls. - Every retried AI call names its reason: a provider error carries its code, a rejected JSON-mode reply carries its own diagnosis (
empty reply,prose without a JSON object,object without a payload key,truncated at the output cap,reply stopped by the content filter,malformed JSON (...)) and logs the whole rejected text, so the event can be replayed fromBot.logalone.finish_reason— not the parse error alone — separates a reply cut by the output cap from one the model ended with broken JSON, and a reply that arrives only after a retry leaves one INFO line instead of silently succeeding. time.sleephas no place in async code; the only acceptable sleeper is_interruptible_sleep.
- Optimize only against measured evidence — never prematurely, never at the cost of readability: a clear 10% win beats an opaque 15% win.
- Keep an optimization self-contained (well under 50 lines), behavior-preserving, and safe under the asyncio event loop and thread concurrency.
- Ask before adding a dependency, changing queue sizes or thread boundaries, touching the core trading loop (
src/app.py,start.py), or changing ChromaDB collection schemas and embedding logic. - Bumping an existing pin is allowed with the full suite,
ruffandpyrightgreen in the same change; the version the venv runs and the line inrequirements.txtmove together, and a deliberate hold keeps a comment naming the conflict (seeCONTRIBUTING.md, "Dependency Changes").
- A refactor is replacement surgery, not additive patching. When a change replaces an implementation, the superseded function, method, class, alias, guard, endpoint, cache prefix, CSS rule or DOM id is removed in the same change. Git history is the archive. A new implementation beside the old one is a defect, not a safe rollout.
- No deprecation provenance. Runtime code never emits
DeprecationWarningorPendingDeprecationWarning, never carries@deprecated, and never adds_v2,_new,legacy_*,old_*,*_compator a compatibility alias for our own retired code. Two boundary migrations are not shims:cleanup_legacy_*removes data, and a payload migration such asstrength_4h → strength_primaryaccepts a shape an external producer can still emit, pinned by a test. - Net-negative production diff. A refactor or retirement task states its budget in the prompt (for example
net diff MUST be <= -150 lines in src/, start.py and scripts/) and proves it withpython scripts/check_net_diff.py --base origin/master --head HEAD --require-negative --quota -150. Tests and docs may grow; the production surface may not. A pure move is reported as RELOCATED, never as a cut. - Zero references means deletion is mandatory. Before deleting a symbol, run
python scripts/check_dead_symbols.py --symbol <name>; it lists every AST reference insrc/,tests/andscripts/. A symbol referenced only by its own test or double is test-only, not live: delete the symbol and the test together, or record the reason inALLOWLISTonly for a documented public entry point or a test seam. "Kept for a future wave" is not a reason. - Retire the whole feature in one change. Sweep four surfaces: the implementation and every call site; its tests, doubles and fixtures; the data-source accessor that existed only for it; every claim surface (README, docs, dashboard copy, AGENTS, skills). A retired feature that still appears in a document is a defect in the same change.
- The gate is not the review.
ruffF401/F811/F841 plusscripts/check_dead_symbols.pycover unused imports, variables and unreferenced definitions. They cannot see a dead branch kept alive by a dynamic string, a framework callback, or a JS/CSS orphan; review those, and document the exception instead of adding a defensive shim. - Zero compatibility leftovers. Delete dead endpoints, cache prefixes, CSS, DOM ids, aliases and retired guards immediately; git history is the archive.
- The decision wire format (signal names, payload fields) is a contract: never change it silently.
- Secrets come from OS/service environment variables (recommended) or optional
keys.env/.env(gitignored); process variables take precedence: never in.py, never in a log. Follow the redaction pattern (_redact_private_key()); never log credentials, private keys or full secret payloads. - Any
eval/exec/subprocess(shell=True)/os.system/pickle.loads/yaml.loadhit insrc/is CRITICAL until proven otherwise. - Validate input with FastAPI/Pydantic models (
Field,Path,Query) instead of hand-parsing dicts; errors must never leak sensitive data. - Use the established patterns: DOMPurify for every dynamic HTML string.
/admin/is the local settings desk:GET /api/settings/statusand the docs are public; config/keys reads and every write are loopback-only (client IP,HostandOriginchecked;CF-Connecting-IPand publicX-Forwarded-Forrejected). No login, session or cookie. - The settings desk never returns a secret value, logs only key names, writes atomically behind an etag conflict check, preserves INI comments/order/line endings, and validates a candidate file with
Config(config_path=temp)beforeos.replace. - A security change is done only when you have exercised the attack vector and shown it fails; report severity, the vulnerable location, the concrete impact, the fix and the proof.
- Any change to the settings-desk access guard is a security change: exercise the loopback, tunnel-header,
HostandOriginpaths before reporting it done.
- Reproduce before fixing. A bug you cannot reproduce is a bug you cannot verify.
- One change, one purpose. Never refactor and fix in the same change; keep the diff minimal and behavior identical beyond the stated fix. A refactor or retirement is the opposite exception: it must remove the superseded implementation in the same change and its production diff must be net-negative (see §10, "Dead code and deletion discipline").
- Fast gate first:
py_compilethe touched files,ruff check src/,python -c "import start",python scripts/check_loose_helpers.py,python scripts/check_config_contract.py,python scripts/check_hardcoded_timeframes.py,python scripts/check_dead_symbols.py,python scripts/check_comment_policy.py, then the targetedpytest tests/<matching>.py -x -q. - Full gate before claiming done:
pytest tests/ -qwith 0 failures and 0 skips, andpyright src start.pywith no new errors. A refactor or retirement also runspython scripts/check_net_diff.py --base origin/master --head HEAD --require-negativeand quotes the net in the change description. - Test isolation: a test double must never default to a live state file, a live journal path (
data/trading/*.jsonl) or a live brain database; point it at a temp directory. - A bug fix ships with a regression test, added to the existing test file for that module rather than a new one.
- Read the diff after every edit: a patch that matched the wrong anchor relocates or truncates code silently.
- Never commit or push without explicit user consent. Run the suite first; commit only with 0 failures.
- Do not touch CI configuration (
.github/workflows/, test/lint settings) unless asked. A gate named in §12.1 is part of the change that adds the rule, so adding that step is the asked-for work; changing unrelated CI is not. - Documentation drift: after moving or renaming a file, run
python scripts/check_agents_md.py(it now coversREADME.md,CONTRIBUTING.mdanddocs/*.md, not only the AGENTS files); after changing the ledger shape, runpython scripts/results_report.pyand update the Results section inREADME.mdin the same change.
Every rule that can be proved mechanically names the gate that proves it, so an omission fails a command instead of a review:
| Rule | Gate |
|---|---|
| Loader keys, template, ini and docs agree | python scripts/check_config_contract.py |
| No timeframe literal outside its definition | python scripts/check_hardcoded_timeframes.py |
| A configured value reaches every consumer | pytest tests/domain_infra/test_config_propagation.py |
| The response contract names only the configured frame | pytest tests/domain_infra/test_config_propagation.py -k response_contract |
| The prompt's position cap is the effective one | pytest tests/domain_infra/test_config_propagation.py -k sizing_cap |
| The prompt has no second definition of the threshold defaults | pytest tests/domain_brain/test_prompt_template.py -k thresholds_match_the_brain_defaults |
| A private helper lives in the class that calls it | python scripts/check_loose_helpers.py |
| Decision wire format unchanged | pytest tests/domain_brain/test_decision_contract.py |
| Paths quoted in AGENTS files exist | python scripts/check_agents_md.py |
| Public copy carries no first person or biography | pytest tests/domain_infra/test_public_copy.py |
| The EV worked example quotes the position cap the runtime enforces | pytest tests/domain_rag_indicators/test_formatters.py -k worked_example |
| The pattern-quality factor the brain learns is the computed one | pytest tests/domain_rag_indicators/test_indicators_and_patterns.py -k factor_the_brain_learns |
| A warning rule is validated by a loss, and a re-store keeps its evidence | pytest tests/domain_brain/test_vector_memory.py -k "corrective or restoring_a_rule" |
| A dashboard KPI reads the uncapped source the other tab uses | pytest tests/domain_infra/test_dashboard_brain.py -k "rule_count or overview_rule_count" |
| A superseded symbol is left behind | python scripts/check_dead_symbols.py |
| A symbol is kept alive only by its own test | python scripts/check_dead_symbols.py (test-only category) |
| A deprecation shim replaces a deletion | python scripts/check_dead_symbols.py (compatibility category) |
| A refactor pull request is additive | python scripts/check_net_diff.py --labels refactor |
| A retired feature keeps its tests, doubles or fixtures | full suite + python scripts/check_dead_symbols.py |
| A comment, a docstring or a bare string returns | python scripts/check_comment_policy.py |
A # type: ignore suppresses nothing |
pyright src start.py (reportUnnecessaryTypeIgnoreComment in the tracked pyrightconfig.json) |
| A fresh entry suppresses itself | pytest tests/domain_infra/test_app_runtime.py -k not_suppressed |
| An entry signal escapes the duplicate or rollback set | pytest tests/domain_infra/test_app_runtime.py -k every_entry_signal |
| A phantom rollback becomes a statistic or a learned trade | pytest tests/domain_trading/test_position_reconciliation.py -k phantom_close |
| The deletion policy or its gate is removed | pytest tests/domain_infra/test_deletion_policy.py |
| The settings desk is reachable off loopback | pytest tests/domain_infra/test_dashboard_settings.py -k "forbidden or loopback" |
| A secret value reaches a settings response or log | pytest tests/domain_infra/test_settings_editor.py -k "never_returns or stays_out" |
The rule compounds: a "the agent forgot X" bug adds a row here and the gate that would have caught it, in the same change.
Root AGENTS.md is canonical for system-wide rules. Package detail lives next to the code so a task reads only the map it needs:
| Area | Detail file | Covers |
|---|---|---|
Cross-cutting src/ contracts (parsing, utils, notifiers, platforms, logger, config, composition, mcp_tools) |
src/AGENTS.md |
Module regression contracts for packages without their own file |
| Trading brain, strategy, monitors, position management | src/trading/AGENTS.md |
TradingBrainService, vector memory, strategy flow, exits |
| Order governance pipeline (guards) | src/trading/guards/AGENTS.md |
Guard chain, fail-closed policy |
| Analysis engine | src/analyzer/AGENTS.md |
Data collection, indicators, prompts, chart vision |
| Indicator library | src/indicators/AGENTS.md |
Numba JIT functions |
| Managers | src/managers/AGENTS.md |
Risk, persistence, SQLite history, providers |
| RAG engine | src/rag/AGENTS.md |
News ingestion, retrieval, priorities |
| Dashboard | src/dashboard/AGENTS.md |
FastAPI app, routers, static UI |
When a change touches one of these areas, read that file before editing; when the rule you need is missing there, add it to the area file rather than growing this one.