Commit Graph

642 Commits

Author SHA1 Message Date
jgrusewski
80099a6799 feat(security): implement OCSP revocation checking
Replace the stub OCSP implementation with a fully functional RFC 6960
compliant revocation checker that:

- Builds OCSP requests using SHA-1 hashes of issuer name/key via the
  ocsp crate's CertId and OneReq types with proper DER encoding
- Sends requests via HTTP POST with correct Content-Type headers
- Parses DER-encoded OCSP responses to extract response status
  (successful/malformed/internal-error/try-later/unauthorized)
- Determines certificate status (Good/Revoked/Unknown) by locating
  the serial number and scanning for ASN.1 context-specific tags
- Caches results in the existing LRU cache with TTL
- Increments Prometheus metrics for all failure paths
2026-02-21 21:29:32 +01:00
jgrusewski
f412efebc8 feat(trading): wire broker config from BrokerConfig parameter 2026-02-21 21:26:14 +01:00
jgrusewski
70b3b74e3a feat(ml): wire unified data loader to feature extractor
Replace the 2-feature placeholder (close, volume) in create_training_samples()
with the full 51-dimension extract_ml_features() pipeline. The UnifiedDataLoader
now converts MarketDataContainers to OHLCVBars and runs the production feature
extractor when use_unified_extractor is enabled, falling back to the basic
2-feature path if extraction fails or the extractor is disabled. Also populates
feature metadata with the 51 named features matching extraction.rs ordering.
2026-02-21 21:22:34 +01:00
jgrusewski
ece9ae11d2 feat(ml): re-enable hyperopt action counting (fixes 62% Sharpe degradation) 2026-02-21 21:20:45 +01:00
jgrusewski
4a8513f813 safety(trading-engine): replace Prometheus static panic with abort fallback 2026-02-21 21:06:33 +01:00
jgrusewski
3e410f29e3 docs: Phase 4 production readiness design and implementation plan
16 tasks across 4 pillars: Safety & Crash Elimination, Trading
Correctness, Compliance & Code Quality, ML Pipeline Quality.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 20:21:01 +01:00
jgrusewski
4f113e6ec9 fix(common): re-enable observability module and fix type errors
Fix three compilation errors in the observability module that had been
commented out due to type errors with tracing_subscriber:

- Fix lifetime issue in set_correlation_id by cloning Arc before async
- Fix Option<CorrelationId> vs CorrelationId type mismatch in get_correlation_id
- Update deprecated opentelemetry_sdk::trace::Config API to builder methods
- Remove unused imports across all observability submodules

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:54:04 +01:00
jgrusewski
15c094c7ee safety: add clippy deny(unwrap_used, expect_used) to api_gateway, backtesting_service
Add #![deny(clippy::unwrap_used, clippy::expect_used)] to api_gateway and
backtesting_service crate roots. The ml and common crates already had these
deny attributes.

Production code fixes:
- api_gateway: replace expect with unwrap_or for cache stats and LRU eviction
- api_gateway: add #[allow] on NonZeroU32 constants and Prometheus metrics
- backtesting_service: replace expect/unwrap with ok_or_else/? for OHLCV
  bar bounds checks and chrono timestamp resampling
- backtesting_service: add #[allow] on Prometheus Lazy metric statics

Test code: cfg_attr(test, allow) at crate root for both crates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:49:13 +01:00
jgrusewski
d35c45e654 feat(trading): wire participation_rate into TWAP slice calculation
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:35:51 +01:00
jgrusewski
5f6386714b feat(trading): document market price integration point for limit order validation
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:34:21 +01:00
jgrusewski
41114c12ff feat(ml): wire PPO/TFT/Mamba2 training in retrain_all_models
Replace three placeholder stubs that returned Err("pending") with
working implementations that create real trainers and run actual
training loops:

- train_ppo: Creates PpoTrainer with conservative defaults,
  loads market data as state vectors, runs PPO training with
  progress callback, saves checkpoint metadata

- train_mamba2: Creates Mamba2Trainer with validated hyperparams,
  generates training/validation tensor pairs, runs MAMBA-2
  sequence training, collects training statistics

- train_tft: Creates TFTTrainer with FileSystemStorage, attempts
  Parquet data loading first with synthetic data fallback,
  runs TFT training with OOM retry support

Also fixes 10 pre-existing compilation errors:
- Import PPOHyperparameters/PPOTrainer -> PpoHyperparameters/PpoTrainer
- Import TFTHyperparameters -> TFTTrainerConfig (correct type name)
- ModelType::LIQUID -> ModelType::LNN (correct enum variant)
- DQNHyperparameters struct literal -> conservative() with overrides
- checkpoint_manager.config() -> direct PathBuf construction
- DQN checkpoint callback 2-arg -> 3-arg (epoch, data, is_best)
- opts partial move -> clone version_tag before unwrap_or_else
- Add catch-all arm for exhaustive ModelType matching
- Add FileSystemStorage import for TFT trainer construction
- Prefix unused variables with underscore

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:28:57 +01:00
jgrusewski
27cc968e94 test(data-acquisition): add pipeline integration tests for validator
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:25:43 +01:00
jgrusewski
3fe6f1cb90 security(api-gateway): add CRL validity period and issuer validation
Replace the TODO placeholder with proper CRL validation that checks:
- thisUpdate is not in the future (CRL not yet valid)
- nextUpdate is not in the past (CRL expired)
- CRL issuer matches the certificate issuer (prevents CRL substitution)

All checks use x509-parser's ASN1Time for accurate time comparison
and log warnings/errors via tracing for operational visibility.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:23:48 +01:00
jgrusewski
786029539d fix(ml): remove mock prediction fallback from ensemble coordinator
Production trading must never rely on simulated predictions. The ensemble
coordinator now requires real model adapters and returns errors when none
are registered or all fail inference, instead of silently falling back to
mock/simulated predictions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:23:42 +01:00
jgrusewski
0e1c8be186 feat(ml): wire TFT safetensors checkpoint save/load
Replace empty placeholder safetensors file with actual model weight
serialization using the VarMap, matching the DQN trainable adapter pattern.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:23:40 +01:00
jgrusewski
828e551f56 security(trading): implement OCSP check as non-blocking with CRL as primary
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:23:38 +01:00
jgrusewski
4c23f8c50c security(api-gateway): implement X.509 signature verification for mTLS
Replace the TODO stub in validate_certificate_chain with full
cryptographic chain-of-trust verification using x509-parser's ring-backed
verify feature:

1. Issuer CN matching -- client cert issuer must equal CA subject CN
2. CA validity period -- reject expired or not-yet-valid CA certificates
3. CA Basic Constraints -- verify the signer actually has cA=true
4. Cryptographic signature -- verify client cert TBS data signature
   against the CA's SubjectPublicKeyInfo (RSA/ECDSA/Ed25519 via ring)

Also enables the "verify" feature on x509-parser and extends the method
signature to accept ca_cert_pem for proper chain validation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:19:35 +01:00
jgrusewski
2fa459cf08 fix(ml): replace unwrap() with ok_or/? in DQN IQN paths
Replace 6 unwrap() calls with safe error handling in DQN IQN code:
- Production: 3 unwrap() on iqn_network/iqn_target_network replaced with
  ok_or_else returning MLError::ModelError for clear diagnostics
- Tests: 2 result.unwrap() replaced with ?, 2 DQN::new().unwrap() replaced
  with ? after changing test signatures to return anyhow::Result<()>

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:12:16 +01:00
jgrusewski
86712a1216 docs: production readiness phase 3 implementation plan — 18 tasks
Bite-sized steps for each task with exact file paths, code snippets,
verification commands, and parallel execution strategy.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:00:43 +01:00
jgrusewski
aa6669ede0 docs: production readiness phase 3 design — 18 tasks across 4 pillars
Safety, live trading, security, and observability gaps identified
from comprehensive codebase audit. Organized for parallel swarm execution.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 18:53:38 +01:00
jgrusewski
6cdffda475 fix(ml): silence unsafe-code warnings on inference adapter Send/Sync impls
Add #[allow(unsafe_code)] on each unsafe impl Send/Sync for the four
inference adapters (DQN, PPO, TFT, Mamba2). The SAFETY comments explain
why these are sound — Mutex provides exclusive access.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 18:39:05 +01:00
jgrusewski
06329a3e96 fix(trading_service): replace placeholder VaR with proper historical simulation
Implement real quantile-based VaR at 95% and 99% confidence, proper
Expected Shortfall (CVaR) as tail mean, sqrt-of-time 10-day scaling,
and safe .get() access instead of array indexing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 18:27:09 +01:00
jgrusewski
434a7653a2 feat(data_acquisition): implement MinIO uploader with object_store
Wire S3-compatible upload/exists/delete using object_store crate.
Fix generate_object_key to return Result instead of panicking.
Add 4 unit tests with InMemory backend.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 18:25:42 +01:00
jgrusewski
abcbf84509 feat(trading_service): wire MLEngine with real EnsembleCoordinator
Replace empty MLEngine struct with actual EnsembleCoordinator from ml
crate. Registers DQN, PPO, TFT, Mamba2 models with configurable
weights loaded from config repository.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 18:24:52 +01:00
jgrusewski
a1ba3ea577 feat: production readiness Phase 1-2 implementation
- fix(trading_engine): replace Prometheus panic! with graceful registration
- fix(trading_service): implement partial fill matching in order book
- feat(trading_service): replace feature extraction stub with real 51-dim pipeline
- feat(trading_service): wire RiskEngine with real VaR calculator
- fix(api_gateway): implement real ML prediction proxy
- feat(data_acquisition): implement DBN data downloader
- feat(data): wire DBN uploader with MinIO integration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 18:21:45 +01:00
jgrusewski
13186424d9 fix(data): implement real Databento stream poll_next
Replace stub Poll::Pending with actual stream polling that reads from
underlying data source and converts DBN messages to MarketEvents.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 18:17:43 +01:00
jgrusewski
ee1cf23972 Merge branch 'worktree-backtesting-vertical-slice'
Backtesting vertical slice: connect 8 disconnected pipeline layers
so DBN files + trained model checkpoints produce real backtest PnL
with trade-by-trade history.

- DBN ProcessedMessage → MarketEvent converter
- DBN replay engine with mpsc channel streaming
- Production 51-dim feature extractor (replacing 3-5 dim local)
- BacktestMLModel wrapper bridging ensemble adapters → MLModel trait
- Model checkpoint loading and registry startup
- Real PositionTracker accounting (weighted avg, partial fills, flips)
- PnL tracking with equity curve and trade history in finalize()
- End-to-end integration test (54 tests total, 0 failures)
2026-02-21 17:35:15 +01:00
jgrusewski
86b6957353 test(backtesting): add end-to-end DBN backtest integration test
Validates full pipeline: DBN converter roundtrip, replay engine streaming,
model loading + prediction, 51-dim feature extraction, and synthetic
backtest with DQN model producing real predictions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 16:06:19 +01:00
jgrusewski
4d3140cfab fix(backtesting): wire PnL tracking and trade history in AdaptiveStrategyRunner
PerformanceTracker now records open entries, computes realized PnL on
position close, tracks equity curve snapshots, and populates trades
and performance_timeline in finalize() instead of returning empty vecs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 16:05:59 +01:00
jgrusewski
b9ead01286 fix(backtesting): implement PositionTracker position accounting and trade recording
Replace stub update_position() and record_trade() with real accounting:
weighted-average entry price, realized PnL on close, partial fills,
position flips (long→short), and trade history recording.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 16:00:07 +01:00
jgrusewski
45eabb71df feat(backtesting): add BacktestMLModel wrapper and registry loader
BacktestMLModel bridges ModelInferenceAdapter → MLModel trait for the
global ModelRegistry. load_models_for_backtest() creates DQN/PPO
adapters from checkpoint files and registers them for inference.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:59:46 +01:00
jgrusewski
b6dfe8e6c4 feat(backtesting): wire production 51-dim feature extractor
Replace local 3-5 feature FeatureExtractor with ProductionFeatureExtractorAdapter
from ml::features. Falls back to legacy extractor during warmup period.
Production extractor produces exactly 51 features matching DQN/PPO training.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:51:02 +01:00
jgrusewski
5891d392e7 feat(backtesting): add DBN replay engine for historical data
DbnReplayEngine loads events and streams them through mpsc channels,
compatible with StrategyTester. Supports from_events() for testing
and from_bytes() stub for DBN file parsing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:50:43 +01:00
jgrusewski
1a5f0a5202 feat(backtesting): add DBN ProcessedMessage to MarketEvent converter
Converts Trade, Ohlcv, and Quote variants from data::ProcessedMessage
to trading_engine::MarketEvent. Handles HardwareTimestamp→DateTime<Utc>,
Decimal→Quantity, and String→Symbol type conversions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:48:17 +01:00
jgrusewski
b2f38ea186 chore: add .worktrees/ to .gitignore
Prevent worktree contents from being tracked.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:32:45 +01:00
jgrusewski
58d2d8ddee fix(data): return None for unsupported DBN event types instead of placeholder trades
The catch-all match arm in convert_to_common_event was creating synthetic
TradeEvent objects with symbol "UNKNOWN", price zero, and trade_id "placeholder"
for any MarketDataEvent variant not explicitly handled (Bar, OrderBook, News, etc.).
These fake trades corrupt downstream analytics pipelines. Now returns None and
logs at debug level instead, allowing callers to filter unsupported types cleanly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:32:02 +01:00
jgrusewski
4069eb473c docs: backtesting vertical slice implementation plan
8-task TDD plan to bridge 8 disconnected layers in the backtesting
pipeline: DBN converter, replay engine, 51-dim feature wiring,
model loader, registry startup, position tracking, PnL tracking,
and end-to-end integration test.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:30:00 +01:00
jgrusewski
4354098d11 docs: Phase 1-2 data pipeline and trading service implementation plan
13-task plan covering data pipeline fixes (Databento stream, data acquisition,
DBN uploader) and trading service core wiring (RiskEngine, MLEngine, VaR,
feature extraction, order matching, API gateway, Prometheus panics).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:25:17 +01:00
jgrusewski
30241e858d docs: backtesting vertical slice production readiness design
8-task plan to bridge disconnected backtesting pipeline layers:
DBN parser → feature extraction → ML inference → position tracking → PnL

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:21:22 +01:00
jgrusewski
e2a712593a docs: full system production readiness design (6-phase plan)
Covers data pipeline, trading service core, broker connectivity
(FIX 4.4 + TWS), execution algorithms, security/compliance, and
observability — based on comprehensive non-ML audit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:18:19 +01:00
jgrusewski
faa7b85cea docs: real-data ensemble backtest and hyperopt deploy design
Two-phase design:
A) Real 6E.FUT data → 4-model ensemble → PaperBroker → P&L metrics
B) Best hyperopt params → train → deploy to ensemble → ValidationHarness

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 15:04:58 +01:00
jgrusewski
2dd3326aec docs: ensemble real inference design and implementation plan
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:58:36 +01:00
jgrusewski
07ab29b8b3 Merge branch 'worktree-full-stack-ml-integration' 2026-02-21 14:56:36 +01:00
jgrusewski
a53daba333 test(paper_trading): add end-to-end pipeline integration test
Replays 100 bars of synthetic price data through:
DQN+PPO ensemble → TradeSignal → PaperBroker → PnLTracker
Verifies finite Sharpe, bounded drawdown, and trade execution.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:30:35 +01:00
jgrusewski
ed320c936b feat(paper_trading): add PaperBroker and PnLTracker for simulated trading
PaperBroker: simulated fills with configurable slippage and commission.
PnLTracker: rolling Sharpe ratio (252-day window), max drawdown, cumulative return.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:26:00 +01:00
jgrusewski
dc3952ce22 feat(ensemble): add TradeSignal type with Buy/Sell/Hold action mapping
TradeSignal converts ensemble predictions to actionable trade signals:
direction > 0.1 → Buy, < -0.1 → Sell, else Hold.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:25:02 +01:00
jgrusewski
b529c0b1db feat(hyperopt): add campaign runner with results persistence
CampaignResults with serde serialization. run_campaign() orchestrates
ArgminOptimizer for DQN hyperopt, saves best_params.json and
campaign_summary.json to timestamped results directory.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:16:02 +01:00
jgrusewski
5dddf365e5 feat(hyperopt): add CampaignConfig with DQN/PPO defaults and GPU limits
Campaign configuration for systematic multi-trial optimization:
- DQN: 50 trials, SHA η=3, 81 max epochs
- PPO: 30 trials, Hyperband, 81 max epochs
- Batch size clamped at 230 (RTX 3050 Ti 4GB VRAM)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:09:59 +01:00
jgrusewski
9e994dba0c test(ensemble): add 4-model inference ensemble integration test
Constructs DQN, PPO, Mamba2, and TFT adapters with small configs,
pre-warms the sequence-based models, then feeds 5 feature vectors
through InferenceEnsemble and verifies bounded predictions from
all 4 models.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:05:49 +01:00
jgrusewski
3bf3a2a0bb feat(ensemble): add InferenceEnsemble coordinator with confidence-weighted aggregation
Lightweight synchronous coordinator that wraps N ModelInferenceAdapter
instances. Aggregates predictions via confidence-weighted voting with
graceful degradation for unready or failing models.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 13:59:18 +01:00