# APEX V16 — Architecture Decisions

## History
- 2026-04-28: Project init dopo diagnosi bug strutturali in V15.
  V15 archiviato (gira ancora sul bruciato fino a chiusura trade aperto).

## Why V16 (not V15.21)
V15 ha accumulato bug strutturali non patchabili senza riscrivere l'orchestrazione:
- 4 punti apertura trade duplicati (~/apex_v15/APEX_PREDATOR_V15.py righe 1674, 1707, 1787, 1864)
- Mismatch nomi chiavi: main scrive entry_struct, Brain leggono market_structure_at_entry
- init_data dict generico con fallback nascosti che falsificano confronti
- manage_exit con signature diversa tra Brain TF e Brain MR
- Dati salvati all'entry (rsi_start) ma mai propagati al Brain
V16 risolve questi problemi via architettura, non via patch.

## What we KEEP from V15 (the good 75%)
**AS-IS** (md5-identical copy):
- broker/topstepx_adapter.py — TopstepX REST adapter custom (4-step bracket)
- core/config_futures.py — Asset specs CME (tick values, contracts, correlation)

**MIGRATED logic, refactored orchestration**:
- Brain TF/MR trading rules (RSI thresholds, ATR-based SL/TP, PA Engine, etc.)
- AI prompts (Gemini, _ask_exit_ai)
- Risk management rules (daily target, hard stop, max contracts, correlation)
- Tech indicators pipeline
- Round-robin Gemini API keys
- Logging JSONL schema

**REWRITTEN** (architectural fixes only):
- Main orchestrator (was 2800+ lines monolith)
- Trade opener (was duplicated 4 times)
- Brain-Main API contract (was untyped dict)
- State persistence (was opaque)

## Modularity (Area 1)
- main.py: entry point, CLI parsing only
- orchestrator.py: async main loop
- core/contracts.py: dataclasses (single source of truth for data shapes)
- core/config.py: runtime config
- core/config_futures.py: asset specs (from V15)
- trading/trade_opener.py: ONE point of trade opening
- trading/trade_tracker.py: track open trades, dispatch to Brain
- trading/trade_closer.py: close + cleanup orphans
- trading/pnl_calculator.py: futures P&L
- trading/risk_manager.py: all risk checks
- broker/topstepx_adapter.py: from V15
- broker/broker_base.py: abstract interface
- brain/brain_base.py: BrainBase interface
- brain/brain_tf.py: Trend Following
- brain/brain_mr.py: Mean Reversion
- brain/ai_client.py: Gemini round-robin
- persistence/state_store.py: state save/load
- persistence/logging_setup.py: JSONL setup

## Contracts (Area 3)
**Golden rule**: NO generic dicts for structured data. Always dataclasses.
- TradeEntry (frozen): immutable snapshot at trade open
- TradeRuntime: mutable runtime state
- BrainContext: what Brain receives (entry + runtime + tech_now)
- BrainDecision: what Brain returns (action + reason + optional fields)

## Modes (Area 4)
- --mode dry: connected, NO trades (logging-only)
- --mode paper: simulated (no broker)
- --mode live --account ineligible: burned account (default dev)
- --mode live --account express: FUNDED (requires interactive confirmation)

State files: state/state_<mode>_<account>.json (separated, never mixed).

## Persistence (Area 5)
- Schema versioned (schema_version: 1)
- Backup pre-save: *.prev.json
- Save on significant events only (open, close, partial, halt)

## Logging (Area 6)
JSONL files per scope:
- trade_log.jsonl: open/close events
- brain_log.jsonl: Brain decisions (HOLD/EXIT) with context
- regime_log.jsonl: regime/structure changes during open trade
- session_log.jsonl: session events (start, halt, target hit)
- error_log.jsonl: exceptions
- system.log: human-readable debug (rotating)

## Risk Manager (Area 7)
Single source of truth: trading/risk_manager.py
Pre-trade checks composed in can_open_trade():
- daily_loss_hard_stop (-1500)
- daily_profit_target (300)
- max_daily_trades (10)
- max_contracts_per_asset
- correlation_block
- force_flat_time (21:08 UTC)
- friday_last_of_month (no entries after 15:00 UTC)
- max_risk_vs_daily_budget (33%)

## Brain Interface (Area 8)
BrainBase:
- evaluate_entry(symbol, tech) -> EntryDecision | None
- manage_exit(ctx: BrainContext) -> BrainDecision

Same signature for TF and MR. No more parameter divergence.

## Reuse philosophy
We DON'T re-invent trading logic. We DO re-architect data flow.
A user reading brain/brain_tf.py should recognize V15's TF rules,
just expressed through clean dataclasses instead of dict fallbacks.
