diff --git a/.coveragerc.json b/.coveragerc.json deleted file mode 100644 index 1b1002b8..00000000 --- a/.coveragerc.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "exclude": [ - "**/node_modules/**", - "**/dist/**", - "**/build/**", - "**/coverage/**", - "**/*.test.ts", - "**/*.test.js", - "**/*.spec.ts", - "**/*.spec.js", - "**/test/**", - "**/tests/**", - "**/__tests__/**", - "**/__mocks__/**", - "**/setup.ts", - "**/setup.js" - ], - "reporters": ["terminal", "html"], - "thresholds": { - "lines": 80, - "functions": 80, - "branches": 80, - "statements": 80 - }, - "outputDir": "coverage" -} diff --git a/.env b/.env index 5c1207eb..d9f981e0 100644 --- a/.env +++ b/.env @@ -4,22 +4,16 @@ # Core Application Settings NODE_ENV=development -LOG_LEVEL=debug -LOG_HIDE_OBJECT=true - -STOCK_BOT_ADMIN_TOKEN=ae8da49a63295865ff9e3d0b4ec012e3ccea73a56d3ff76ae6c7276d9d539ed3 -STOCK_BOT_SERVICE_TOKEN=df6510947397dff96078f0b330c82779aff741583e862069c0e37a2be14a4f03 +LOG_LEVEL=info # Data Service Configuration DATA_SERVICE_PORT=2001 # Queue and Worker Configuration -WORKER_COUNT=1 -WORKER_CONCURRENCY=2 +WORKER_COUNT=4 +WORKER_CONCURRENCY=20 -WEBSHARE_API_KEY= -WEBSHARE_ROTATING_PROXY_URL= -WEBSHARE_API_URL=https://proxy.webshare.io/api/v2/ +WEBSHARE_API_KEY=y8ay534rcbybdkk3evnzmt640xxfhy7252ce2t98 # =========================================== # DATABASE CONFIGURATIONS @@ -27,31 +21,31 @@ WEBSHARE_API_URL=https://proxy.webshare.io/api/v2/ # Dragonfly/Redis Configuration DRAGONFLY_HOST=localhost -DRAGONFLY_PORT=6380 +DRAGONFLY_PORT=6379 DRAGONFLY_PASSWORD= # PostgreSQL Configuration POSTGRES_HOST=localhost -POSTGRES_PORT=5433 -POSTGRES_DATABASE=trading_bot_dev -POSTGRES_USERNAME=dev_user -POSTGRES_PASSWORD=dev_pass +POSTGRES_PORT=5432 +POSTGRES_DB=stockbot +POSTGRES_USER=postgres +POSTGRES_PASSWORD=postgres POSTGRES_SSL=false # QuestDB Configuration QUESTDB_HOST=localhost -QUESTDB_PORT=9100 +QUESTDB_PORT=9000 QUESTDB_DB=qdb -QUESTDB_USERNAME=admin +QUESTDB_USER=admin QUESTDB_PASSWORD=quest # MongoDB Configuration MONGODB_HOST=localhost -MONGODB_PORT=27018 -MONGODB_DATABASE=stock_dev -MONGODB_USERNAME=dev_admin -MONGODB_PASSWORD=dev_mongo_pass -MONGODB_URI=mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin +MONGODB_PORT=27017 +MONGODB_DB=stockbot +MONGODB_USER= +MONGODB_PASSWORD= +MONGODB_URI=mongodb://localhost:27017/stockbot # =========================================== # DATA PROVIDER CONFIGURATIONS @@ -154,6 +148,7 @@ SOURCE_MAPS=true # =========================================== # Docker-specific settings (used in docker-compose) +COMPOSE_PROJECT_NAME=stock-bot DOCKER_BUILDKIT=1 # =========================================== @@ -164,17 +159,6 @@ DOCKER_BUILDKIT=1 TZ=UTC # Application Metadata -APP_NAME="Stock Bot Platform" +APP_NAME=Stock Bot Platform APP_VERSION=1.0.0 -APP_DESCRIPTION="Advanced Stock Trading and Analysis Platform" - -# PostgreSQL -DATABASE_POSTGRES_HOST=localhost -DATABASE_POSTGRES_PORT=5433 -DATABASE_POSTGRES_DATABASE=trading_bot_dev -DATABASE_POSTGRES_USER=dev_user -DATABASE_POSTGRES_PASSWORD=dev_pass -QUESTDB_HTTP_PORT=9100 -QUESTDB_PG_PORT=8813 -QUESTDB_ILP_PORT=9010 -QUEUE_ENABLE_SCHEDULED_JOBS=false +APP_DESCRIPTION=Advanced Stock Trading and Analysis Platform diff --git a/.env.complete b/.env.complete new file mode 100644 index 00000000..4aea1942 --- /dev/null +++ b/.env.complete @@ -0,0 +1,242 @@ +# ======================================================================= +# Stock Bot Platform Environment Configuration +# ======================================================================= + +# Core Application Settings +NODE_ENV=development +PORT=3001 +APP_NAME=stock-bot +APP_VERSION=1.0.0 + +# ======================================================================= +# DATABASE CONFIGURATIONS +# ======================================================================= + +# PostgreSQL - Operational Data (orders, positions, strategies) +POSTGRES_HOST=localhost +POSTGRES_PORT=5432 +POSTGRES_DATABASE=trading_bot +POSTGRES_USERNAME=trading_user +POSTGRES_PASSWORD=trading_pass_dev +DB_HOST=localhost +DB_PORT=5432 +DB_NAME=trading_bot +DB_USER=trading_user +DB_PASSWORD=trading_pass_dev +DB_POOL_MIN=2 +DB_POOL_MAX=10 +DB_POOL_IDLE_TIMEOUT=30000 +DB_SSL=false +DB_SSL_REJECT_UNAUTHORIZED=true +DB_QUERY_TIMEOUT=30000 +DB_CONNECTION_TIMEOUT=5000 + +# QuestDB - Time-series Data (OHLCV, indicators, performance) +QUESTDB_HOST=localhost +QUESTDB_HTTP_PORT=9000 +QUESTDB_PG_PORT=8812 +QUESTDB_INFLUX_PORT=9009 +QUESTDB_USER= +QUESTDB_PASSWORD= +QUESTDB_CONNECTION_TIMEOUT=5000 +QUESTDB_REQUEST_TIMEOUT=30000 +QUESTDB_RETRY_ATTEMPTS=3 +QUESTDB_TLS_ENABLED=false +QUESTDB_DEFAULT_DATABASE=qdb +QUESTDB_TELEMETRY_ENABLED=false + +# MongoDB - Document Storage (sentiment, raw docs, unstructured data) +MONGODB_HOST=localhost +MONGODB_PORT=27017 +MONGODB_DATABASE=trading_documents +MONGODB_USERNAME=trading_admin +MONGODB_PASSWORD=trading_mongo_dev +MONGODB_AUTH_SOURCE=admin +MONGODB_URI= +MONGODB_MAX_POOL_SIZE=10 +MONGODB_MIN_POOL_SIZE=0 +MONGODB_MAX_IDLE_TIME=30000 +MONGODB_CONNECT_TIMEOUT=10000 +MONGODB_SOCKET_TIMEOUT=30000 +MONGODB_SERVER_SELECTION_TIMEOUT=5000 +MONGODB_TLS=false +MONGODB_RETRY_WRITES=true +MONGODB_JOURNAL=true +MONGODB_READ_PREFERENCE=primary +MONGODB_WRITE_CONCERN=majority + +# Dragonfly - Redis Replacement (caching and events) +DRAGONFLY_HOST=localhost +DRAGONFLY_PORT=6379 +DRAGONFLY_PASSWORD= +DRAGONFLY_USERNAME= +DRAGONFLY_DATABASE=0 +DRAGONFLY_MAX_RETRIES=3 +DRAGONFLY_RETRY_DELAY=50 +DRAGONFLY_CONNECT_TIMEOUT=10000 +DRAGONFLY_COMMAND_TIMEOUT=5000 +DRAGONFLY_POOL_SIZE=10 +DRAGONFLY_POOL_MIN=1 +DRAGONFLY_POOL_MAX=20 +DRAGONFLY_TLS=false +DRAGONFLY_ENABLE_KEEPALIVE=true +DRAGONFLY_KEEPALIVE_INTERVAL=60 +DRAGONFLY_CLUSTER_MODE=false +DRAGONFLY_CLUSTER_NODES= +DRAGONFLY_MAX_MEMORY=2gb +DRAGONFLY_CACHE_MODE=true + +# ======================================================================= +# MONITORING & LOGGING CONFIGURATIONS +# ======================================================================= + +# Logging Configuration +LOG_LEVEL=debug +LOG_FORMAT=json +LOG_CONSOLE=true +LOG_FILE=false +LOG_FILE_PATH=logs +LOG_FILE_MAX_SIZE=20m +LOG_FILE_MAX_FILES=14 +LOG_FILE_DATE_PATTERN=YYYY-MM-DD +LOG_ERROR_FILE=true +LOG_ERROR_STACK=true +LOG_PERFORMANCE=false +LOG_SQL_QUERIES=false +LOG_HTTP_REQUESTS=true +LOG_STRUCTURED=true +LOG_TIMESTAMP=true +LOG_CALLER_INFO=false +LOG_SILENT_MODULES= +LOG_VERBOSE_MODULES= +LOG_SERVICE_NAME=stock-bot +LOG_SERVICE_VERSION=1.0.0 +LOG_ENVIRONMENT=development + +# Loki - Log Aggregation +LOKI_HOST=localhost +LOKI_PORT=3100 +LOKI_URL= +LOKI_USERNAME= +LOKI_PASSWORD= +LOKI_TENANT_ID= +LOKI_PUSH_TIMEOUT=10000 +LOKI_BATCH_SIZE=1024 +LOKI_BATCH_WAIT=1000 +LOKI_RETENTION_PERIOD=30d +LOKI_MAX_CHUNK_AGE=1h +LOKI_TLS_ENABLED=false +LOKI_TLS_INSECURE=false +LOKI_DEFAULT_LABELS= +LOKI_SERVICE_LABEL=stock-bot +LOKI_ENVIRONMENT_LABEL=development + +# Prometheus - Metrics Collection +PROMETHEUS_HOST=localhost +PROMETHEUS_PORT=9090 +PROMETHEUS_URL= +PROMETHEUS_USERNAME= +PROMETHEUS_PASSWORD= +PROMETHEUS_SCRAPE_INTERVAL=15s +PROMETHEUS_EVALUATION_INTERVAL=15s +PROMETHEUS_RETENTION_TIME=15d +PROMETHEUS_TLS_ENABLED=false +PROMETHEUS_TLS_INSECURE=false + +# Grafana - Visualization +GRAFANA_HOST=localhost +GRAFANA_PORT=3000 +GRAFANA_URL= +GRAFANA_ADMIN_USER=admin +GRAFANA_ADMIN_PASSWORD=admin +GRAFANA_ALLOW_SIGN_UP=false +GRAFANA_SECRET_KEY= +GRAFANA_DATABASE_TYPE=sqlite3 +GRAFANA_DATABASE_URL= +GRAFANA_DISABLE_GRAVATAR=true +GRAFANA_ENABLE_GZIP=true + +# ======================================================================= +# DATA PROVIDER CONFIGURATIONS +# ======================================================================= + +# Default Data Provider +DEFAULT_DATA_PROVIDER=alpaca + +# Alpaca Markets +ALPACA_ENABLED=true +ALPACA_API_KEY=your_alpaca_key_here +ALPACA_SECRET_KEY=your_alpaca_secret_here +ALPACA_BASE_URL=https://paper-api.alpaca.markets +ALPACA_DATA_URL=https://data.alpaca.markets +ALPACA_PAPER_TRADING=true + +# Polygon.io +POLYGON_ENABLED=false +POLYGON_API_KEY=your_polygon_key_here +POLYGON_BASE_URL=https://api.polygon.io + +# Yahoo Finance +YAHOO_ENABLED=true +YAHOO_BASE_URL=https://query1.finance.yahoo.com + +# IEX Cloud +IEX_ENABLED=false +IEX_API_KEY=your_iex_key_here +IEX_BASE_URL=https://cloud.iexapis.com + +# Alpha Vantage +ALPHA_VANTAGE_ENABLED=false +ALPHA_VANTAGE_API_KEY=demo + +# Data Provider Settings +DATA_PROVIDER_TIMEOUT=30000 +DATA_PROVIDER_RETRIES=3 +DATA_PROVIDER_RETRY_DELAY=1000 +DATA_CACHE_ENABLED=true +DATA_CACHE_TTL=300 +DATA_CACHE_MAX_SIZE=1000 + +# ======================================================================= +# TRADING & RISK MANAGEMENT +# ======================================================================= + +# Trading Configuration +PAPER_TRADING=true +MAX_POSITION_SIZE=0.1 +MAX_DAILY_LOSS=1000 + +# Risk Management +RISK_MAX_POSITION_SIZE=0.25 +RISK_MAX_LEVERAGE=2.0 +RISK_DEFAULT_STOP_LOSS=0.02 +RISK_DEFAULT_TAKE_PROFIT=0.06 +RISK_MAX_DRAWDOWN=0.10 +RISK_MAX_CONSECUTIVE_LOSSES=5 +RISK_POSITION_SIZING_METHOD=fixed_percentage +RISK_CIRCUIT_BREAKER_ENABLED=true +RISK_CIRCUIT_BREAKER_THRESHOLD=0.05 +RISK_CIRCUIT_BREAKER_COOLDOWN=3600000 +RISK_ALLOW_WEEKEND_TRADING=false +RISK_MARKET_HOURS_ONLY=true + +# ======================================================================= +# FEATURE FLAGS +# ======================================================================= +ENABLE_ML_SIGNALS=false +ENABLE_SENTIMENT_ANALYSIS=false +ENABLE_SOCIAL_SIGNALS=false +ENABLE_OPTIONS_TRADING=false +ENABLE_CRYPTO_TRADING=false +ENABLE_BACKTESTING=true +ENABLE_PAPER_TRADING=true +ENABLE_LIVE_TRADING=false + +# ======================================================================= +# DEVELOPMENT & DEBUGGING +# ======================================================================= +DEBUG_MODE=true +VERBOSE_LOGGING=true +MOCK_DATA_PROVIDERS=false +ENABLE_API_RATE_LIMITING=true +ENABLE_REQUEST_LOGGING=true diff --git a/.env.dev.example b/.env.dev.example deleted file mode 100644 index e5f23f70..00000000 --- a/.env.dev.example +++ /dev/null @@ -1,52 +0,0 @@ -# Development environment (isolated local stack on non-overlapping ports) -# Copy to .env.dev and fill in your QA read-only MongoDB password + local tokens. -# Run services with: bun --env-file=.env.dev run dev - -NODE_ENV=development - -# Auth tokens (generate with: openssl rand -hex 32) -STOCK_BOT_ADMIN_TOKEN= -STOCK_BOT_SERVICE_TOKEN= -STOCK_BOT_READ_TOKEN= -STOCK_BOT_HTTP_HOST=127.0.0.1 -STOCK_BOT_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000,http://localhost:5173 -STOCK_BOT_AUTH_DISABLED=false - -# Dev PostgreSQL (isolated container on port 5433 - master records written by dev data-pipeline) -POSTGRES_HOST=localhost -POSTGRES_PORT=5433 -POSTGRES_DATABASE=trading_bot_dev -POSTGRES_USERNAME=dev_user -POSTGRES_PASSWORD=dev_pass -POSTGRES_SSL=false -DATABASE_POSTGRES_HOST=localhost -DATABASE_POSTGRES_PORT=5433 -DATABASE_POSTGRES_DATABASE=trading_bot_dev -DATABASE_POSTGRES_USER=dev_user -DATABASE_POSTGRES_PASSWORD=dev_pass - -# Dev MongoDB (isolated container on port 27018 - used by dev data-ingestion for writes) -MONGODB_HOST=localhost -MONGODB_PORT=27018 -MONGODB_DATABASE=stock_dev -MONGODB_USERNAME=dev_admin -MONGODB_PASSWORD=dev_mongo_pass -MONGODB_URI=mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin - -# QA MongoDB READ-ONLY connection (used by dev data-pipeline to read ingested provider data) -MONGODB_READ_URI=mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock - -# Dev Dragonfly / QuestDB / Queue -DRAGONFLY_HOST=localhost -DRAGONFLY_PORT=6380 -QUESTDB_HOST=localhost -QUESTDB_PORT=9100 -QUESTDB_HTTP_PORT=9100 -QUESTDB_PG_PORT=8813 -QUESTDB_ILP_PORT=9010 -QUEUE_ENABLE_SCHEDULED_JOBS=false - -# DuckDB per-connection budget (prevents default 80% host-RAM allocation) -DUCKDB_MEMORY_LIMIT=2GB -DUCKDB_THREADS=2 -DUCKDB_TEMP_DIR=/tmp/stock-bot-duckdb-dev diff --git a/.env.docker b/.env.docker new file mode 100644 index 00000000..4e8dcebd --- /dev/null +++ b/.env.docker @@ -0,0 +1,144 @@ +# Docker Environment Configuration +# This file contains environment variables used by Docker Compose + +# ============================================================================= +# CONTAINER NETWORK SETTINGS +# ============================================================================= +COMPOSE_PROJECT_NAME=stock-bot +NETWORK_NAME=trading-bot-network + +# ============================================================================= +# DATABASE CONTAINER SETTINGS +# ============================================================================= + +# PostgreSQL Container +POSTGRES_DB=trading_bot +POSTGRES_USER=trading_user +POSTGRES_PASSWORD=trading_pass_secure +POSTGRES_INITDB_ARGS=--encoding=UTF-8 + +# MongoDB Container +MONGO_INITDB_ROOT_USERNAME=trading_admin +MONGO_INITDB_ROOT_PASSWORD=trading_mongo_secure +MONGO_INITDB_DATABASE=trading_documents + +# QuestDB Container +QDB_TELEMETRY_ENABLED=false + +# Dragonfly Container +DRAGONFLY_MAXMEMORY=4gb +DRAGONFLY_PROACTOR_THREADS=8 + +# ============================================================================= +# MONITORING CONTAINER SETTINGS +# ============================================================================= + +# Grafana Container +GF_SECURITY_ADMIN_USER=admin +GF_SECURITY_ADMIN_PASSWORD=secure_grafana_password +GF_USERS_ALLOW_SIGN_UP=false +GF_PATHS_PROVISIONING=/etc/grafana/provisioning +GF_DISABLE_GRAVATAR=true + +# Prometheus Container +PROMETHEUS_CONFIG_FILE=/etc/prometheus/prometheus.yml +PROMETHEUS_STORAGE_PATH=/prometheus +PROMETHEUS_WEB_ENABLE_LIFECYCLE=true + +# ============================================================================= +# ADMIN INTERFACE CONTAINER SETTINGS +# ============================================================================= + +# PgAdmin Container +PGADMIN_DEFAULT_EMAIL=admin@tradingbot.local +PGADMIN_DEFAULT_PASSWORD=secure_pgadmin_password +PGADMIN_CONFIG_SERVER_MODE=False +PGADMIN_DISABLE_POSTFIX=true + +# Mongo Express Container +ME_CONFIG_MONGODB_ADMINUSERNAME=trading_admin +ME_CONFIG_MONGODB_ADMINPASSWORD=trading_mongo_secure +ME_CONFIG_MONGODB_SERVER=mongodb +ME_CONFIG_MONGODB_PORT=27017 +ME_CONFIG_BASICAUTH_USERNAME=admin +ME_CONFIG_BASICAUTH_PASSWORD=secure_mongo_express_password + +# Redis Insight Container +REDIS_HOSTS=local:dragonfly:6379 + +# ============================================================================= +# VOLUME MOUNT PATHS +# ============================================================================= + +# Data Volume Paths (adjust these for your host system) +POSTGRES_DATA_PATH=./data/postgres +QUESTDB_DATA_PATH=./data/questdb +MONGODB_DATA_PATH=./data/mongodb +DRAGONFLY_DATA_PATH=./data/dragonfly +PROMETHEUS_DATA_PATH=./data/prometheus +GRAFANA_DATA_PATH=./data/grafana +LOKI_DATA_PATH=./data/loki +PGADMIN_DATA_PATH=./data/pgadmin + +# Config Volume Paths +PROMETHEUS_CONFIG_PATH=./monitoring/prometheus +GRAFANA_CONFIG_PATH=./monitoring/grafana +LOKI_CONFIG_PATH=./monitoring/loki + +# Database Init Paths +POSTGRES_INIT_PATH=./database/postgres/init +MONGODB_INIT_PATH=./database/mongodb/init + +# ============================================================================= +# PORT MAPPINGS (HOST:CONTAINER) +# ============================================================================= + +# Database Ports +POSTGRES_PORT=5432 +QUESTDB_HTTP_PORT=9000 +QUESTDB_PG_PORT=8812 +QUESTDB_INFLUX_PORT=9009 +MONGODB_PORT=27017 +DRAGONFLY_PORT=6379 + +# Monitoring Ports +PROMETHEUS_PORT=9090 +GRAFANA_PORT=3000 +LOKI_PORT=3100 + +# Admin Interface Ports +PGADMIN_PORT=8080 +MONGO_EXPRESS_PORT=8081 +REDIS_INSIGHT_PORT=8001 + +# ============================================================================= +# HEALTH CHECK SETTINGS +# ============================================================================= + +# Health Check Intervals +HEALTHCHECK_INTERVAL=30s +HEALTHCHECK_TIMEOUT=10s +HEALTHCHECK_RETRIES=3 +HEALTHCHECK_START_PERIOD=60s + +# ============================================================================= +# RESOURCE LIMITS +# ============================================================================= + +# Memory Limits (uncomment and adjust for production) +# POSTGRES_MEMORY_LIMIT=2g +# QUESTDB_MEMORY_LIMIT=4g +# MONGODB_MEMORY_LIMIT=2g +# DRAGONFLY_MEMORY_LIMIT=4g +# PROMETHEUS_MEMORY_LIMIT=2g +# GRAFANA_MEMORY_LIMIT=512m +# LOKI_MEMORY_LIMIT=1g + +# CPU Limits (uncomment and adjust for production) +# POSTGRES_CPU_LIMIT=1 +# QUESTDB_CPU_LIMIT=2 +# MONGODB_CPU_LIMIT=1 +# DRAGONFLY_CPU_LIMIT=2 +# PROMETHEUS_CPU_LIMIT=1 +# GRAFANA_CPU_LIMIT=0.5 +# LOKI_CPU_LIMIT=1 diff --git a/.env.example b/.env.example index 953c7c24..3415413e 100644 --- a/.env.example +++ b/.env.example @@ -1,17 +1,43 @@ -# Generate each token independently: openssl rand -hex 32 -# Tokens stay on the server; never put them in VITE_* variables or URLs. -STOCK_BOT_ADMIN_TOKEN= -STOCK_BOT_SERVICE_TOKEN= -# Optional read-only dashboard/API access. -STOCK_BOT_READ_TOKEN= -STOCK_BOT_HTTP_HOST=127.0.0.1 -STOCK_BOT_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000 -# Explicit loopback-only development escape hatch. Forbidden in production. -STOCK_BOT_AUTH_DISABLED=false +# Environment Configuration NODE_ENV=development -# Provider credentials are optional; configure only the providers you enable. -EOD_API_KEY= -QM_USERNAME= -QM_PASSWORD= -IB_ACCOUNT= -IB_PROXY_URL= +PORT=3000 + +# Database Configuration +QUESTDB_HOST=localhost +QUESTDB_PORT=9000 +QUESTDB_DATABASE=qdb + +POSTGRES_HOST=localhost +POSTGRES_PORT=5432 +POSTGRES_DATABASE=stockbot +POSTGRES_USERNAME=postgres +POSTGRES_PASSWORD=password + +DRAGONFLY_HOST=localhost +DRAGONFLY_PORT=6379 +DRAGONFLY_PASSWORD= + +# API Keys (Add your actual keys here) +ALPHA_VANTAGE_API_KEY=demo +ALPACA_API_KEY=your_alpaca_key_here +ALPACA_SECRET_KEY=your_alpaca_secret_here + +# Trading Configuration +PAPER_TRADING=true +MAX_POSITION_SIZE=0.1 +MAX_DAILY_LOSS=1000 + +# Logging +LOG_LEVEL=debug +LOG_CONSOLE=true +LOKI_HOST=localhost +LOKI_PORT=3100 +LOKI_USERNAME= +LOKI_PASSWORD= +LOKI_RETENTION_DAYS=30 +LOKI_LABELS=environment=development,service=stock-bot +LOKI_BATCH_SIZE=100 + +# Feature Flags +ENABLE_ML_SIGNALS=false +ENABLE_SENTIMENT_ANALYSIS=false diff --git a/.env.prod b/.env.prod new file mode 100644 index 00000000..2aa8d1d7 --- /dev/null +++ b/.env.prod @@ -0,0 +1,233 @@ +# ======================================================================= +# Stock Bot Platform Production Environment Configuration +# ======================================================================= + +# Core Application Settings +NODE_ENV=production +PORT=3001 +APP_NAME=stock-bot +APP_VERSION=1.0.0 + +# ======================================================================= +# DATABASE CONFIGURATIONS +# ======================================================================= + +# PostgreSQL - Operational Data (orders, positions, strategies) +DB_HOST=${DB_HOST} +DB_PORT=${DB_PORT:-5432} +DB_NAME=${DB_NAME} +DB_USER=${DB_USER} +DB_PASSWORD=${DB_PASSWORD} +DB_POOL_MIN=5 +DB_POOL_MAX=20 +DB_POOL_IDLE_TIMEOUT=60000 +DB_SSL=true +DB_SSL_REJECT_UNAUTHORIZED=true +DB_QUERY_TIMEOUT=30000 +DB_CONNECTION_TIMEOUT=10000 + +# QuestDB - Time-series Data (OHLCV, indicators, performance) +QUESTDB_HOST=${QUESTDB_HOST} +QUESTDB_HTTP_PORT=${QUESTDB_HTTP_PORT:-9000} +QUESTDB_PG_PORT=${QUESTDB_PG_PORT:-8812} +QUESTDB_INFLUX_PORT=${QUESTDB_INFLUX_PORT:-9009} +QUESTDB_USER=${QUESTDB_USER} +QUESTDB_PASSWORD=${QUESTDB_PASSWORD} +QUESTDB_CONNECTION_TIMEOUT=10000 +QUESTDB_REQUEST_TIMEOUT=60000 +QUESTDB_RETRY_ATTEMPTS=5 +QUESTDB_TLS_ENABLED=true +QUESTDB_DEFAULT_DATABASE=qdb +QUESTDB_TELEMETRY_ENABLED=false + +# MongoDB - Document Storage (sentiment, raw docs, unstructured data) +MONGODB_HOST=${MONGODB_HOST} +MONGODB_PORT=${MONGODB_PORT:-27017} +MONGODB_DATABASE=${MONGODB_DATABASE} +MONGODB_USERNAME=${MONGODB_USERNAME} +MONGODB_PASSWORD=${MONGODB_PASSWORD} +MONGODB_AUTH_SOURCE=admin +MONGODB_URI=${MONGODB_URI} +MONGODB_MAX_POOL_SIZE=50 +MONGODB_MIN_POOL_SIZE=5 +MONGODB_MAX_IDLE_TIME=60000 +MONGODB_CONNECT_TIMEOUT=30000 +MONGODB_SOCKET_TIMEOUT=60000 +MONGODB_SERVER_SELECTION_TIMEOUT=10000 +MONGODB_TLS=true +MONGODB_RETRY_WRITES=true +MONGODB_JOURNAL=true +MONGODB_READ_PREFERENCE=primaryPreferred +MONGODB_WRITE_CONCERN=majority + +# Dragonfly - Redis Replacement (caching and events) +DRAGONFLY_HOST=${DRAGONFLY_HOST} +DRAGONFLY_PORT=${DRAGONFLY_PORT:-6379} +DRAGONFLY_PASSWORD=${DRAGONFLY_PASSWORD} +DRAGONFLY_USERNAME=${DRAGONFLY_USERNAME} +DRAGONFLY_DATABASE=0 +DRAGONFLY_MAX_RETRIES=5 +DRAGONFLY_RETRY_DELAY=100 +DRAGONFLY_CONNECT_TIMEOUT=30000 +DRAGONFLY_COMMAND_TIMEOUT=10000 +DRAGONFLY_POOL_SIZE=50 +DRAGONFLY_POOL_MIN=5 +DRAGONFLY_POOL_MAX=100 +DRAGONFLY_TLS=true +DRAGONFLY_ENABLE_KEEPALIVE=true +DRAGONFLY_KEEPALIVE_INTERVAL=30 +DRAGONFLY_CLUSTER_MODE=false +DRAGONFLY_CLUSTER_NODES= +DRAGONFLY_MAX_MEMORY=8gb +DRAGONFLY_CACHE_MODE=true + +# ======================================================================= +# MONITORING & LOGGING CONFIGURATIONS +# ======================================================================= + +# Logging Configuration (Production - Less verbose) +LOG_LEVEL=info +LOG_FORMAT=json +LOG_CONSOLE=false +LOG_FILE=true +LOG_FILE_PATH=/var/log/stock-bot +LOG_FILE_MAX_SIZE=100m +LOG_FILE_MAX_FILES=30 +LOG_FILE_DATE_PATTERN=YYYY-MM-DD +LOG_ERROR_FILE=true +LOG_ERROR_STACK=false +LOG_PERFORMANCE=true +LOG_SQL_QUERIES=false +LOG_HTTP_REQUESTS=false +LOG_STRUCTURED=true +LOG_TIMESTAMP=true +LOG_CALLER_INFO=false +LOG_SILENT_MODULES= +LOG_VERBOSE_MODULES= +LOG_SERVICE_NAME=stock-bot +LOG_SERVICE_VERSION=1.0.0 +LOG_ENVIRONMENT=production + +# Loki - Log Aggregation +LOKI_HOST=${LOKI_HOST} +LOKI_PORT=${LOKI_PORT:-3100} +LOKI_URL=${LOKI_URL} +LOKI_USERNAME=${LOKI_USERNAME} +LOKI_PASSWORD=${LOKI_PASSWORD} +LOKI_TENANT_ID=${LOKI_TENANT_ID} +LOKI_PUSH_TIMEOUT=30000 +LOKI_BATCH_SIZE=2048 +LOKI_BATCH_WAIT=5000 +LOKI_RETENTION_PERIOD=90d +LOKI_MAX_CHUNK_AGE=2h +LOKI_TLS_ENABLED=true +LOKI_TLS_INSECURE=false +LOKI_DEFAULT_LABELS= +LOKI_SERVICE_LABEL=stock-bot +LOKI_ENVIRONMENT_LABEL=production + +# Prometheus - Metrics Collection +PROMETHEUS_HOST=${PROMETHEUS_HOST} +PROMETHEUS_PORT=${PROMETHEUS_PORT:-9090} +PROMETHEUS_URL=${PROMETHEUS_URL} +PROMETHEUS_USERNAME=${PROMETHEUS_USERNAME} +PROMETHEUS_PASSWORD=${PROMETHEUS_PASSWORD} +PROMETHEUS_SCRAPE_INTERVAL=30s +PROMETHEUS_EVALUATION_INTERVAL=30s +PROMETHEUS_RETENTION_TIME=90d +PROMETHEUS_TLS_ENABLED=true +PROMETHEUS_TLS_INSECURE=false + +# Grafana - Visualization +GRAFANA_HOST=${GRAFANA_HOST} +GRAFANA_PORT=${GRAFANA_PORT:-3000} +GRAFANA_URL=${GRAFANA_URL} +GRAFANA_ADMIN_USER=${GRAFANA_ADMIN_USER} +GRAFANA_ADMIN_PASSWORD=${GRAFANA_ADMIN_PASSWORD} +GRAFANA_ALLOW_SIGN_UP=false +GRAFANA_SECRET_KEY=${GRAFANA_SECRET_KEY} +GRAFANA_DATABASE_TYPE=postgres +GRAFANA_DATABASE_URL=${GRAFANA_DATABASE_URL} +GRAFANA_DISABLE_GRAVATAR=true +GRAFANA_ENABLE_GZIP=true + +# ======================================================================= +# DATA PROVIDER CONFIGURATIONS +# ======================================================================= + +# Default Data Provider +DEFAULT_DATA_PROVIDER=alpaca + +# Alpaca Markets (Production) +ALPACA_ENABLED=true +ALPACA_API_KEY=${ALPACA_API_KEY} +ALPACA_SECRET_KEY=${ALPACA_SECRET_KEY} +ALPACA_BASE_URL=https://api.alpaca.markets +ALPACA_DATA_URL=https://data.alpaca.markets +ALPACA_PAPER_TRADING=false + +# Polygon.io +POLYGON_ENABLED=${POLYGON_ENABLED:-false} +POLYGON_API_KEY=${POLYGON_API_KEY} +POLYGON_BASE_URL=https://api.polygon.io + +# Yahoo Finance +YAHOO_ENABLED=${YAHOO_ENABLED:-false} +YAHOO_BASE_URL=https://query1.finance.yahoo.com + +# IEX Cloud +IEX_ENABLED=${IEX_ENABLED:-false} +IEX_API_KEY=${IEX_API_KEY} +IEX_BASE_URL=https://cloud.iexapis.com + +# Data Provider Settings (Production) +DATA_PROVIDER_TIMEOUT=60000 +DATA_PROVIDER_RETRIES=5 +DATA_PROVIDER_RETRY_DELAY=2000 +DATA_CACHE_ENABLED=true +DATA_CACHE_TTL=60 +DATA_CACHE_MAX_SIZE=10000 + +# ======================================================================= +# TRADING & RISK MANAGEMENT (Production) +# ======================================================================= + +# Trading Configuration +PAPER_TRADING=false +MAX_POSITION_SIZE=${MAX_POSITION_SIZE:-0.05} +MAX_DAILY_LOSS=${MAX_DAILY_LOSS:-10000} + +# Risk Management (Stricter for production) +RISK_MAX_POSITION_SIZE=${RISK_MAX_POSITION_SIZE:-0.10} +RISK_MAX_LEVERAGE=${RISK_MAX_LEVERAGE:-1.5} +RISK_DEFAULT_STOP_LOSS=${RISK_DEFAULT_STOP_LOSS:-0.015} +RISK_DEFAULT_TAKE_PROFIT=${RISK_DEFAULT_TAKE_PROFIT:-0.045} +RISK_MAX_DRAWDOWN=${RISK_MAX_DRAWDOWN:-0.05} +RISK_MAX_CONSECUTIVE_LOSSES=${RISK_MAX_CONSECUTIVE_LOSSES:-3} +RISK_POSITION_SIZING_METHOD=volatility_adjusted +RISK_CIRCUIT_BREAKER_ENABLED=true +RISK_CIRCUIT_BREAKER_THRESHOLD=0.02 +RISK_CIRCUIT_BREAKER_COOLDOWN=7200000 +RISK_ALLOW_WEEKEND_TRADING=false +RISK_MARKET_HOURS_ONLY=true + +# ======================================================================= +# FEATURE FLAGS (Production) +# ======================================================================= +ENABLE_ML_SIGNALS=${ENABLE_ML_SIGNALS:-false} +ENABLE_SENTIMENT_ANALYSIS=${ENABLE_SENTIMENT_ANALYSIS:-false} +ENABLE_SOCIAL_SIGNALS=${ENABLE_SOCIAL_SIGNALS:-false} +ENABLE_OPTIONS_TRADING=${ENABLE_OPTIONS_TRADING:-false} +ENABLE_CRYPTO_TRADING=${ENABLE_CRYPTO_TRADING:-false} +ENABLE_BACKTESTING=true +ENABLE_PAPER_TRADING=false +ENABLE_LIVE_TRADING=true + +# ======================================================================= +# PRODUCTION SETTINGS +# ======================================================================= +DEBUG_MODE=false +VERBOSE_LOGGING=false +MOCK_DATA_PROVIDERS=false +ENABLE_API_RATE_LIMITING=true +ENABLE_REQUEST_LOGGING=false diff --git a/.env.prod.example b/.env.prod.example deleted file mode 100644 index 3a2091d3..00000000 --- a/.env.prod.example +++ /dev/null @@ -1,51 +0,0 @@ -# Production environment template (for separate production server deployment) -# Copy to .env.prod on the production host and supply strong, unique credentials. - -NODE_ENV=production - -# Auth tokens (required; generate independently with: openssl rand -hex 32) -STOCK_BOT_ADMIN_TOKEN= -STOCK_BOT_SERVICE_TOKEN= -STOCK_BOT_READ_TOKEN= -STOCK_BOT_HTTP_HOST=127.0.0.1 -STOCK_BOT_ALLOWED_ORIGINS= -STOCK_BOT_AUTH_DISABLED=false - -# Production PostgreSQL -POSTGRES_HOST= -POSTGRES_PORT=5432 -POSTGRES_DATABASE=trading_bot_prod -POSTGRES_USERNAME= -POSTGRES_PASSWORD= -POSTGRES_SSL=true -DATABASE_POSTGRES_HOST= -DATABASE_POSTGRES_PORT=5432 -DATABASE_POSTGRES_DATABASE=trading_bot_prod -DATABASE_POSTGRES_USER= -DATABASE_POSTGRES_PASSWORD= - -# Production MongoDB (ingestion write URI + optional read-only URI for data-pipeline) -MONGODB_HOST= -MONGODB_PORT=27017 -MONGODB_DATABASE=stock -MONGODB_USERNAME= -MONGODB_PASSWORD= -MONGODB_URI= -MONGODB_READ_URI= -MONGODB_CACHE_GB=16 - -# Production Dragonfly / QuestDB -DRAGONFLY_HOST= -DRAGONFLY_PORT=6379 -DRAGONFLY_PASSWORD= -DRAGONFLY_MAXMEMORY=8gb -QUESTDB_HOST= -QUESTDB_PORT=9000 -QUESTDB_PG_PORT=8812 -QUESTDB_ILP_PORT=9009 - -# Provider credentials (configure only enabled providers) -EOD_API_KEY= -QM_USERNAME= -QM_PASSWORD= -IB_ACCOUNT= diff --git a/.env.production b/.env.production new file mode 100644 index 00000000..dfd7a4d0 --- /dev/null +++ b/.env.production @@ -0,0 +1,135 @@ +# Production Environment Configuration +NODE_ENV=production +PORT=3001 + +# ============================================================================= +# DATABASE CONFIGURATIONS +# ============================================================================= + +# PostgreSQL - Operational data (orders, positions, strategies) +DB_HOST=postgres +DB_PORT=5432 +DB_NAME=trading_bot +DB_USER=trading_user +DB_PASSWORD=${POSTGRES_PASSWORD} +DB_POOL_MIN=5 +DB_POOL_MAX=20 +DB_SSL=true +DB_SSL_REJECT_UNAUTHORIZED=true + +# QuestDB - Time-series data (OHLCV, indicators, performance) +QUESTDB_HOST=questdb +QUESTDB_HTTP_PORT=9000 +QUESTDB_PG_PORT=8812 +QUESTDB_INFLUX_PORT=9009 +QUESTDB_DEFAULT_DATABASE=qdb +QUESTDB_TELEMETRY_ENABLED=false +QUESTDB_TLS_ENABLED=true + +# MongoDB - Document storage (sentiment, raw docs, unstructured data) +MONGODB_HOST=mongodb +MONGODB_PORT=27017 +MONGODB_DATABASE=trading_documents +MONGODB_USERNAME=${MONGODB_ROOT_USERNAME} +MONGODB_PASSWORD=${MONGODB_ROOT_PASSWORD} +MONGODB_AUTH_SOURCE=admin +MONGODB_TLS=true +MONGODB_RETRY_WRITES=true + +# Dragonfly - Redis replacement for caching and events +DRAGONFLY_HOST=dragonfly +DRAGONFLY_PORT=6379 +DRAGONFLY_PASSWORD=${DRAGONFLY_PASSWORD} +DRAGONFLY_DATABASE=0 +DRAGONFLY_MAX_MEMORY=4gb +DRAGONFLY_CACHE_MODE=true +DRAGONFLY_TLS=true + +# ============================================================================= +# MONITORING & OBSERVABILITY +# ============================================================================= + +# Prometheus - Metrics collection +PROMETHEUS_HOST=prometheus +PROMETHEUS_PORT=9090 +PROMETHEUS_SCRAPE_INTERVAL=30s +PROMETHEUS_RETENTION_TIME=90d +PROMETHEUS_TLS_ENABLED=true + +# Grafana - Visualization +GRAFANA_HOST=grafana +GRAFANA_PORT=3000 +GRAFANA_ADMIN_USER=${GRAFANA_ADMIN_USER} +GRAFANA_ADMIN_PASSWORD=${GRAFANA_ADMIN_PASSWORD} +GRAFANA_ALLOW_SIGN_UP=false +GRAFANA_SECRET_KEY=${GRAFANA_SECRET_KEY} +GRAFANA_DATABASE_TYPE=postgres +GRAFANA_DISABLE_GRAVATAR=true + +# Loki - Log aggregation +LOKI_HOST=loki +LOKI_PORT=3100 +LOKI_RETENTION_PERIOD=90d +LOKI_BATCH_SIZE=2048 +LOKI_TLS_ENABLED=true + +# ============================================================================= +# ADMIN INTERFACES (Disabled in production) +# ============================================================================= + +# PgAdmin - PostgreSQL GUI (disabled in production) +PGADMIN_HOST=pgadmin +PGADMIN_PORT=8080 +PGADMIN_DEFAULT_EMAIL=${PGADMIN_EMAIL} +PGADMIN_DEFAULT_PASSWORD=${PGADMIN_PASSWORD} +PGADMIN_SERVER_MODE=true +PGADMIN_MASTER_PASSWORD_REQUIRED=true + +# Mongo Express - MongoDB GUI (disabled in production) +MONGO_EXPRESS_HOST=mongo-express +MONGO_EXPRESS_PORT=8081 +MONGO_EXPRESS_MONGODB_SERVER=mongodb +MONGO_EXPRESS_BASICAUTH_USERNAME=${MONGO_EXPRESS_USER} +MONGO_EXPRESS_BASICAUTH_PASSWORD=${MONGO_EXPRESS_PASSWORD} + +# Redis Insight - Dragonfly/Redis GUI (disabled in production) +REDIS_INSIGHT_HOST=redis-insight +REDIS_INSIGHT_PORT=8001 +REDIS_INSIGHT_REDIS_HOSTS=production:dragonfly:6379 + +# ============================================================================= +# DATA PROVIDERS & TRADING +# ============================================================================= + +# API Keys (Set from environment variables) +ALPHA_VANTAGE_API_KEY=${ALPHA_VANTAGE_API_KEY} +ALPACA_API_KEY=${ALPACA_API_KEY} +ALPACA_SECRET_KEY=${ALPACA_SECRET_KEY} +POLYGON_API_KEY=${POLYGON_API_KEY} +IEX_API_KEY=${IEX_API_KEY} +YAHOO_FINANCE_API_KEY=${YAHOO_FINANCE_API_KEY} + +# Trading Configuration +PAPER_TRADING=false +MAX_POSITION_SIZE=0.05 +MAX_DAILY_LOSS=5000 +RISK_MANAGEMENT_ENABLED=true + +# ============================================================================= +# APPLICATION SETTINGS +# ============================================================================= + +# Logging +LOG_LEVEL=info +LOG_FORMAT=json + +# Feature Flags +ENABLE_ML_SIGNALS=true +ENABLE_SENTIMENT_ANALYSIS=true +ENABLE_RISK_MONITORING=true +ENABLE_PERFORMANCE_TRACKING=true + +# Security +CORS_ALLOWED_ORIGINS=${CORS_ALLOWED_ORIGINS} +JWT_SECRET=${JWT_SECRET} +API_RATE_LIMIT=1000 diff --git a/.env.qa.example b/.env.qa.example deleted file mode 100644 index 224fd764..00000000 --- a/.env.qa.example +++ /dev/null @@ -1,51 +0,0 @@ -# QA environment (existing local stack backed by stock-bot_mongodb_data & stock-bot_postgres_data) -# Copy your existing .env to .env.qa and set NODE_ENV=qa. -# Run services with: bun --env-file=.env.qa run dev - -NODE_ENV=qa - -# Auth tokens (generate with: openssl rand -hex 32) -STOCK_BOT_ADMIN_TOKEN= -STOCK_BOT_SERVICE_TOKEN= -STOCK_BOT_READ_TOKEN= -STOCK_BOT_HTTP_HOST=127.0.0.1 -STOCK_BOT_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000 -STOCK_BOT_AUTH_DISABLED=false - -# QA PostgreSQL (existing container on port 5432) -POSTGRES_HOST=localhost -POSTGRES_PORT=5432 -POSTGRES_DATABASE=trading_bot -POSTGRES_USERNAME=trading_user -POSTGRES_PASSWORD=trading_pass_dev -POSTGRES_SSL=false -DATABASE_POSTGRES_HOST=localhost -DATABASE_POSTGRES_PORT=5432 -DATABASE_POSTGRES_DATABASE=trading_bot -DATABASE_POSTGRES_USER=trading_user -DATABASE_POSTGRES_PASSWORD=trading_pass_dev - -# QA MongoDB (existing container on port 27017 - holds full ingested provider dataset) -MONGODB_HOST=localhost -MONGODB_PORT=27017 -MONGODB_DATABASE=stock -MONGODB_USERNAME=trading_admin -MONGODB_PASSWORD=trading_mongo_dev -MONGODB_URI=mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin -# Optional: restrict QA data-pipeline to read-only MongoDB credentials too -# MONGODB_READ_URI=mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock - -# QA Dragonfly / QuestDB / Queue -DRAGONFLY_HOST=localhost -DRAGONFLY_PORT=6379 -QUESTDB_HOST=localhost -QUESTDB_PORT=9000 -QUESTDB_HTTP_PORT=9000 -QUESTDB_PG_PORT=8812 -QUESTDB_ILP_PORT=9009 -QUEUE_ENABLE_SCHEDULED_JOBS=true - -# DuckDB per-worker budget on quant (prevents default 80% host-RAM allocation) -DUCKDB_MEMORY_LIMIT=6GB -DUCKDB_THREADS=4 -DUCKDB_TEMP_DIR=/mnt/data/stockbot/tmp/duckdb diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000..f3f3b157 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,81 @@ +# Dependencies +node_modules/ +**/node_modules/ + +# Build outputs +dist/ +build/ +**/dist/ +**/build/ +.next/ +**/.next/ + +# Cache directories +.turbo/ +**/.turbo/ +.cache/ +**/.cache/ + +# Environment files +.env +.env.local +.env.production +.env.staging +**/.env* + +# Lock files +package-lock.json +yarn.lock +bun.lockb +pnpm-lock.yaml + +# Logs +*.log +logs/ +**/logs/ + +# Database files +*.db +*.sqlite +*.sqlite3 + +# Temporary files +*.tmp +*.temp +.DS_Store +Thumbs.db + +# Generated files +*.d.ts +**/*.d.ts + +# JavaScript files (we're focusing on TypeScript) +*.js +*.mjs +!.eslintrc.js +!eslint.config.js + +# Scripts and config directories +scripts/ +monitoring/ +database/ +docker-compose*.yml +Dockerfile* + +# Documentation +*.md +docs/ + +# Test coverage +coverage/ +**/coverage/ + +# IDE/Editor files +.vscode/ +.idea/ +*.swp +*.swo + +# Angular specific +**/.angular/ +**/src/polyfills.ts diff --git a/.gitignore b/.gitignore index e3ebee38..60fc5506 100644 --- a/.gitignore +++ b/.gitignore @@ -1,123 +1,105 @@ -# Environment files (the two private local-development configs are intentionally tracked) -.env -.env.* -!/.env -!/apps/stock/web-app/.env -!.env.example -!.env.*.example - -# Dependencies -node_modules/ -.pnp -.pnp.js - -# Production builds -dist/ -build/ -.next/ -*.js.map -*.d.ts -!apps/stock/engine/index.d.ts - - -# Logs -npm-debug.log* -yarn-debug.log* -yarn-error.log* -bun-debug.log* -bun-error.log* -*.log - -# Runtime data -pids -*.pid -*.seed -*.pid.lock -*.tsbuildinfo - -# Coverage directory used by tools like istanbul -coverage/ -*.lcov - -# Dependency directories -.pnpm-store/ - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional stylelint cache -.stylelintcache - -# Microbundle cache -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# parcel-bundler cache (https://parceljs.org/) -.cache -.parcel-cache - -# Next.js build output -.next - -# Nuxt.js build / generate output -.nuxt - -# Storybook build outputs -.out -.storybook-out - -# Temporary folders -tmp/ -temp/ - -# Editor directories and files -.idea/ -*.swp -*.swo -*~ - -# OS generated files -.DS_Store -.DS_Store? -._* -.Spotlight-V100 -.Trashes -ehthumbs.db -Thumbs.db - -# Trading bot specific -.data/ -.backtest-results/ -.logs/ -.old/ -.mongo/ -.chat/ -*.db -*.sqlite -*.sqlite3 - -# Turbo -.turbo -*.tsbuildinfo - -# AI -.serena/ -.claude/ -docs/configuration-standardization.md - -# Rust -target/ +# Dependencies +node_modules/ +.pnp +.pnp.js + +# Production builds +dist/ +build/ +.next/ +*.js.map +*.d.ts + + +# Logs +npm-debug.log* +yarn-debug.log* +yarn-error.log* +bun-debug.log* +bun-error.log* +*.log + +# Runtime data +pids +*.pid +*.seed +*.pid.lock +*.tsbuildinfo + +# Coverage directory used by tools like istanbul +coverage/ +*.lcov + +# Dependency directories +.pnpm-store/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next + +# Nuxt.js build / generate output +.nuxt + +# Storybook build outputs +.out +.storybook-out + +# Temporary folders +tmp/ +temp/ + +# Editor directories and files +.idea/ +*.swp +*.swo +*~ + +# OS generated files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Trading bot specific +.data/ +.backtest-results/ +.logs/ +.old/ +.mongo/ +.chat/ +*.db +*.sqlite +*.sqlite3 + +# Turbo +.turbo diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e3e93681..a70399f3 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,42 +1,19 @@ -stages: - - build - - test - - deploy - - review - - dast - - staging - - canary - - production - - incremental rollout 10% - - incremental rollout 25% - - incremental rollout 50% - - incremental rollout 100% - - performance - - cleanup -sast: - stage: test -include: - - template: Auto-DevOps.gitlab-ci.yml - -repository-check: - stage: test - image: rust:1.88-bookworm - services: - - name: postgres:16-alpine - alias: postgres - - name: redis:7-alpine - alias: redis - variables: - POSTGRES_DB: stock_bot_safety - POSTGRES_USER: fixture - POSTGRES_PASSWORD: fixture - PIPELINE_TEST_DATABASE_URL: postgres://fixture:fixture@postgres:5432/stock_bot_safety - BACKTEST_TEST_REDIS_URL: redis://redis:6379/15 - before_script: - - apt-get update && apt-get install -y --no-install-recommends nodejs unzip - - curl -fsSL https://bun.sh/install | bash -s "bun-v1.2.17" - - export PATH="/root/.bun/bin:$PATH" - - bun install --frozen-lockfile - script: - - bun run check - - bun run test:postgres +stages: +- build +- test +- deploy +- review +- dast +- staging +- canary +- production +- incremental rollout 10% +- incremental rollout 25% +- incremental rollout 50% +- incremental rollout 100% +- performance +- cleanup +sast: + stage: test +include: +- template: Auto-DevOps.gitlab-ci.yml diff --git a/.prettierrc b/.prettierrc index 9a6f6aee..4073a4fc 100644 --- a/.prettierrc +++ b/.prettierrc @@ -10,9 +10,7 @@ "bracketSpacing": true, "bracketSameLine": false, "quoteProps": "as-needed", - "plugins": [ - "@ianvs/prettier-plugin-sort-imports" - ], + "plugins": ["@ianvs/prettier-plugin-sort-imports"], "importOrder": [ "^(node:.*|fs|path|crypto|url|os|util|events|stream|buffer|child_process|cluster|http|https|net|tls|dgram|dns|readline|repl|vm|zlib|querystring|punycode|assert|timers|constants)$", "", @@ -24,20 +22,5 @@ "^\\.(?!/?$)", "^\\./?$" ], - "importOrderParserPlugins": [ - "typescript", - "decorators-legacy" - ], - "overrides": [ - { - "files": "**/*.tsx", - "options": { - "importOrderParserPlugins": [ - "typescript", - "jsx", - "decorators-legacy" - ] - } - } - ] + "importOrderParserPlugins": ["typescript", "decorators-legacy"] } diff --git a/.vscode/mcp.json b/.vscode/mcp.json deleted file mode 100644 index 0e0dcd23..00000000 --- a/.vscode/mcp.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - -} \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index e17d8648..00000000 --- a/AGENTS.md +++ /dev/null @@ -1,48 +0,0 @@ -# Stock Bot — Studio Agent Guide - -## Runtime & Tooling -- Use **Bun** (`bun`, `bun test`, `bun run`) and **Turbo** (`turbo`) for builds, scripts, and tests. -- Build: `bun run build` -- Typecheck: `bun run typecheck` -- Tests: `bun test` (PostgreSQL safety tests require `PIPELINE_TEST_DATABASE_URL` pointing to a dedicated `stock_bot_safety*` database, configured via `/home/boki/.studio/test-env/stock-bot.env`). - -### Check Gates & Sandbox Split -- **Why `bun run check` (`scripts/check.ts`) cannot pass end-to-end inside the agent sandbox**: worktree `.git` metadata lives outside the sandbox (breaking `audit:secrets` and the worktree-git tooling tests in `scripts/test/audit-secrets-repo.test.ts`, `strategy-packaging.test.ts`, `benchmark-research.test.ts`, `benchmark-replay.test.ts`, and `benchmark-sma.test.ts`), and sandbox network isolation blocks host PostgreSQL `127.0.0.1:5432` for `PIPELINE_TEST_DATABASE_URL` suites. -- **Sandbox-runnable gates (run locally before handoff)**: `bun run typecheck`, `bun run test:contracts`, `bun run lint:check`, `CARGO_BUILD_JOBS=2 bun run test:native`, `bun run test:utils`, `bun run test:calculations`, and targeted non-git/non-Postgres tests (e.g. `bun test scripts/test/security.test.ts`). -- **Studio unsandboxed verification (`bun run build` and `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test`)**: authoritatively covers `build`, `audit:secrets` (via `scripts/test/audit-secrets-repo.test.ts`), `test:tooling` (including all worktree-git tests), `test:integration`, and PostgreSQL-backed tests. Sandbox-only `.git`/PostgreSQL failures are not a review deadlock when Studio's unsandboxed run is green, and agents must never skip or mock out those checks to make them pass inside the sandbox. -- **Full host verification outside a sandbox**: run `CARGO_BUILD_JOBS=2 bun run check`. - -## Environments (`dev` / `qa` / `prod`) - -| Environment | `NODE_ENV` | Compose File | PostgreSQL | MongoDB (Write) | MongoDB (Read / Pipeline) | Dragonfly | QuestDB | -| --- | --- | --- | --- | --- | --- | --- | --- | -| **dev** | `development` | `docker-compose.dev.yml` | `localhost:5433` (`trading_bot_dev`) | `localhost:27018` (`stock_dev`) | `localhost:27017` (`stock`, **read-only** via `MONGODB_READ_URI`) | `localhost:6380` | `localhost:9100` | -| **qa** | `qa` | `docker-compose.yml` | `localhost:5432` (`trading_bot`) | `localhost:27017` (`stock`) | `localhost:27017` (`stock`) | `localhost:6379` | `localhost:9000` | -| **prod** | `production` | `docker-compose.prod.yml` | Separate host (env-driven) | Separate host (env-driven) | Separate host (`MONGODB_READ_URI` optional) | Env-driven | Env-driven | - -## Data Flow & Strict Safety Rules -1. **QA MongoDB (`stock-bot_mongodb_data` on `localhost:27017`, database `stock`) holds the full ingested multi-billion-document dataset. NEVER drop, reset, or write to QA MongoDB from `dev` or automated tests.** - - Never run `docker compose down -v` against `docker-compose.yml`. - - `./scripts/docker.sh reset` is hard-blocked for `qa` and `prod`. -2. **`data-pipeline` reads MongoDB and writes master records to PostgreSQL.** - - `apps/stock/data-pipeline` initializes its container with `mongoReadOnly: true`, which uses `database.mongodb.readUri` (`MONGODB_READ_URI`) when set and rejects all MongoDB write/index/collection-mutation operations at the client layer. - - In `dev`, `data-pipeline` reads QA MongoDB read-only (`studio_stock_bot_read@stock`) and writes master records into isolated dev PostgreSQL (`localhost:5433/trading_bot_dev`). -3. **`data-ingestion` writes raw provider data to MongoDB.** - - In `dev`, `data-ingestion` must target isolated dev MongoDB (`localhost:27018/stock_dev`). - - `assertEnvironmentSafety()` in `apps/stock/config/src/env-safety.ts` blocks `development` services from opening writable connections to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`). -4. **Tests** must never mutate QA Postgres (`trading_bot`) or QA MongoDB (`stock`). Use isolated schemas in `stock_bot_safety*` or in-memory/testcontainer databases. - -## Key Modules -- `apps/stock/data-ingestion`: Provider crawlers/ingesters writing raw documents into MongoDB. -- `apps/stock/data-pipeline`: Processes raw MongoDB documents into normalized master records in PostgreSQL (`exchanges`, `symbols`, `provider_exchange_mappings`, `provider_mappings`, `sync_status`). -- `apps/stock/config` & `libs/core/config`: Environment config schemas (`development`, `qa`, `test`, `production`) and startup safety guards. -- `apps/stock/web-api` & `apps/stock/web-app`: API and dashboard UI. -- `apps/stock/orchestrator` & `apps/stock/engine`: Backtest/paper/live orchestration and Rust execution engine. - -## Documentation -- `docs/README.md`: Documentation index and navigation map. -- `docs/PLATFORM-PLAN.md`: Target platform architecture and locked decisions (`D1`–`D12`). -- `docs/MILESTONES.md`: Ordered `M0`–`M5` build plan, file targets, and exit criteria. -- `docs/DATA-CONTRACTS.md`: Empirical MongoDB provider rules, PostgreSQL security master, DuckDB/Parquet, and QuestDB `10.2.0` schemas. -- `docs/VALIDATION-AND-RIGOR.md`: Canonical metrics, `trial_ledger`, DSR/PBO/CPCV math, 6-month vault + post-2023 recency gate, and IBKR Margin (`USD`/`CAD`) execution rules. -- `docs/servers.md`: Hardware and container topology (`quant` `10.0.0.51`, `9900K`, `TrueNAS`, local dev). diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index d9461a34..00000000 --- a/CLAUDE.md +++ /dev/null @@ -1,34 +0,0 @@ -# CLAUDE.md — Stock Bot Engineering & Quant Guide - -Read [AGENTS.md](./AGENTS.md) first for mandatory environment and database safety rules, then [docs/README.md](./docs/README.md) for the platform architecture and active milestone checklist. - -## 1. Canonical Documentation -- [AGENTS.md](./AGENTS.md) — Runtime commands (`bun`, `turbo`), `dev` vs `qa` port isolation, and strict QA MongoDB/PostgreSQL protection rules. -- [docs/PLATFORM-PLAN.md](./docs/PLATFORM-PLAN.md) — North-star architecture and locked design decisions (`D1`–`D12`). -- [docs/MILESTONES.md](./docs/MILESTONES.md) — Ordered implementation roadmap (`M0` → `M5`) with file targets and falsifiable exit criteria. -- [docs/DATA-CONTRACTS.md](./docs/DATA-CONTRACTS.md) — Empirical schemas and adjustment/PIT rules for all 31 QA MongoDB collections, PostgreSQL security master (`instruments`, `instrument_listings`, `corporate_actions`), DuckDB/Parquet, and QuestDB `10.2.0`. -- [docs/VALIDATION-AND-RIGOR.md](./docs/VALIDATION-AND-RIGOR.md) — `@stock-bot/calculations` single-source metric formulas, append-only `trial_ledger`, $\hat{N}$ Deflated Sharpe, CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, and IBKR Margin (`USD`/`CAD`) execution rules. -- [docs/servers.md](./docs/servers.md) — Hardware & container topology (`quant` `10.0.0.51`, `9900K` execution host, `TrueNAS`, local dev). - -## 2. Non-Negotiable Architecture & Data Invariants -1. **Protect QA Data:** Never drop, reset, or write to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`) from `dev` or tests. Query QA MongoDB strictly read-only via `MONGODB_READ_URI` (`studio_stock_bot_read`). -2. **Tooling:** Use `bun` (`bun run build`, `bun run typecheck`, `bun test`) and `turbo`. Native Rust execution lives in `apps/stock/engine` (N-API addon). -3. **Identity & Point-in-Time (`PIT`):** - - Key market, fundamental, and feature records by `listing_id` (`instrument_listings`), never bare ticker strings. - - Enforce `known_at <= as_of` on every non-price join; never filter universes on current `is_active` or `delisted_at IS NULL`. - - Respect empirical provider adjustment semantics (`eodPrices` has raw OHLC + **split-adjusted volume**; `eodIntraday1M` has **split-adjusted OHLC**; `qmPrices` has raw OHLC + raw `sharevolume`). -4. **Storage Split (`D1`):** - - **DuckDB + Hive Parquet** owns `1d` bars, corporate actions, PIT fundamentals/earnings/shorts/macro, `1d` FX (`CAD.FOREX`), and versioned feature matrices. - - **QuestDB `10.2.0`** owns `1m`/`5m`/`1h` intraday and hot streaming bars (`listing_id SYMBOL CAPACITY 65536 NOCACHE`). -5. **Single Financial Authority (`D2`):** - - The Rust `engine` (`apps/stock/engine`) is the sole authority for fills, fees, margin interest, corporate-action accounting, and equity curves across backtest, paper, and live. - - `@stock-bot/calculations` (`libs/calculations`) is the sole authority for Sharpe, Sortino, Calmar, MaxDD, turnover, IC, DSR, and PBO. -6. **Anti-Overfitting Controls:** - - Every candidate evaluation writes an immutable row to PostgreSQL `trial_ledger` *before* returning metrics. - - Research agents (`sb-research.*`) must never access raw dataset export routes or the air-gapped rolling 6-month vault. - -## 3. Working Style -- Deliver complete, production-grade code without mocks, stubs, or `TODO` placeholders. -- Check actual repository files and data contracts before changing interfaces; batch independent reads, searches, and edits in parallel. -- Validate changes with `bun run typecheck`, `bun run audit:secrets`, and targeted `bun test` suites (using `/home/boki/.studio/test-env/stock-bot.env` for PostgreSQL safety tests). -- Keep communication direct, concise, and technical—skip basics and generic boilerplate. diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index 11d01203..00000000 --- a/Cargo.lock +++ /dev/null @@ -1,1658 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "ahash" -version = "0.8.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" -dependencies = [ - "cfg-if", - "const-random", - "getrandom 0.4.3", - "once_cell", - "serde", - "version_check", - "zerocopy", -] - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "anyhow" -version = "1.0.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" - -[[package]] -name = "approx" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" -dependencies = [ - "num-traits", -] - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "bitvec" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" -dependencies = [ - "funty", - "radium", - "tap", - "wyz", -] - -[[package]] -name = "bson" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3f109694c4f45353972af96bf97d8a057f82e2d6e496457f4d135b9867a518c" -dependencies = [ - "ahash", - "base64", - "bitvec", - "getrandom 0.3.4", - "hex", - "indexmap", - "js-sys", - "rand 0.9.5", - "serde_bytes", - "simdutf8", - "thiserror 2.0.21", - "time", - "uuid", -] - -[[package]] -name = "bumpalo" -version = "3.20.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" - -[[package]] -name = "bytes" -version = "1.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" - -[[package]] -name = "cc" -version = "1.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" -dependencies = [ - "find-msvc-tools", - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "const-random" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d38d4bb3e79c716fd0330d8da84171b0135e59e01076e99f22b75a64c56e952c" -dependencies = [ - "const-random-macro", -] - -[[package]] -name = "const-random-macro" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d66bb491e9fc48cb3fed9d57df886880a751d540d645ebc86b6d9d35b8fa8457" -dependencies = [ - "getrandom 0.4.3", - "tiny-keccak", -] - -[[package]] -name = "convert_case" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "crossbeam" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e71406cd8807725f7ac2f999a4cdd32e98f829fdf65f528343cebf945e41df1e" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-epoch", - "crossbeam-queue", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-queue" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - -[[package]] -name = "ctor" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501" -dependencies = [ - "quote", - "syn 2.0.119", -] - -[[package]] -name = "curate-etl" -version = "0.1.0" -dependencies = [ - "bson", - "parquet", -] - -[[package]] -name = "dashmap" -version = "5.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" -dependencies = [ - "cfg-if", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core", -] - -[[package]] -name = "deranged" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" - -[[package]] -name = "engine" -version = "0.1.0" -dependencies = [ - "anyhow", - "async-trait", - "chrono", - "crossbeam", - "dashmap", - "nalgebra 0.32.6", - "napi", - "napi-build", - "napi-derive", - "num-bigint 0.4.6", - "num-rational", - "num-traits", - "parking_lot", - "rand 0.8.8", - "rand_distr", - "rust_decimal", - "serde", - "serde_json", - "statrs", - "thiserror 1.0.69", - "tokio", - "tracing", - "tracing-subscriber", - "uuid", -] - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "errno" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" - -[[package]] -name = "funty" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-core", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "r-efi 5.3.0", - "wasip2", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "r-efi 6.0.0", - "wasm-bindgen", -] - -[[package]] -name = "half" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" -dependencies = [ - "cfg-if", - "crunchy", - "num-traits", - "zerocopy", -] - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - -[[package]] -name = "hashbrown" -version = "0.17.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown 0.17.2", -] - -[[package]] -name = "itoa" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" - -[[package]] -name = "jobserver" -version = "0.1.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" -dependencies = [ - "getrandom 0.4.3", - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "lazy_static" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "libloading" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" -dependencies = [ - "cfg-if", - "windows-link", -] - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" - -[[package]] -name = "matrixmultiply" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" -dependencies = [ - "autocfg", - "rawpointer", -] - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "mio" -version = "1.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" -dependencies = [ - "libc", - "wasi", - "windows-sys", -] - -[[package]] -name = "nalgebra" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d506eb7e08d6329505faa8a3a00a5dcc6de9f76e0c77e4b75763ae3c770831ff" -dependencies = [ - "approx", - "matrixmultiply", - "nalgebra-macros 0.1.0", - "num-complex", - "num-rational", - "num-traits", - "rand 0.8.8", - "rand_distr", - "simba 0.6.0", - "typenum", -] - -[[package]] -name = "nalgebra" -version = "0.32.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5c17de023a86f59ed79891b2e5d5a94c705dbe904a5b5c9c952ea6221b03e4" -dependencies = [ - "approx", - "matrixmultiply", - "nalgebra-macros 0.2.2", - "num-complex", - "num-rational", - "num-traits", - "simba 0.8.1", - "typenum", -] - -[[package]] -name = "nalgebra-macros" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01fcc0b8149b4632adc89ac3b7b31a12fb6099a0317a4eb2ebff574ef7de7218" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "nalgebra-macros" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "254a5372af8fc138e36684761d3c0cdb758a4410e938babcff1c860ce14ddbfc" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "napi" -version = "2.16.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3" -dependencies = [ - "bitflags", - "chrono", - "ctor", - "napi-derive", - "napi-sys", - "once_cell", - "serde", - "serde_json", - "tokio", -] - -[[package]] -name = "napi-build" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb4c45ca811160461dba7eccc68b66702ddb5c9f30afb16007caac3c0eb6e2a" - -[[package]] -name = "napi-derive" -version = "2.16.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c" -dependencies = [ - "cfg-if", - "convert_case", - "napi-derive-backend", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "napi-derive-backend" -version = "1.0.75" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf" -dependencies = [ - "convert_case", - "once_cell", - "proc-macro2", - "quote", - "regex", - "semver", - "syn 2.0.119", -] - -[[package]] -name = "napi-sys" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3" -dependencies = [ - "libloading", -] - -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "num-bigint" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-bigint" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-complex" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" - -[[package]] -name = "num-integer" -version = "0.1.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-rational" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" -dependencies = [ - "num-bigint 0.4.6", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", - "libm", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - -[[package]] -name = "parquet" -version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6701f0dd63f5ee23a0f1f2865ff76825c301759d6ab649e3e5686cc32d066957" -dependencies = [ - "ahash", - "bytes", - "chrono", - "half", - "hashbrown 0.17.2", - "num-bigint 0.5.1", - "num-integer", - "num-traits", - "seq-macro", - "twox-hash", - "zstd", -] - -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - -[[package]] -name = "pin-project-lite" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" - -[[package]] -name = "pkg-config" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" - -[[package]] -name = "powerfmt" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "radium" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" - -[[package]] -name = "rand" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "rand_distr" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" -dependencies = [ - "num-traits", - "rand 0.8.8", -] - -[[package]] -name = "rawpointer" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" - -[[package]] -name = "rust_decimal" -version = "1.43.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a" -dependencies = [ - "arrayvec", - "num-traits", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "safe_arch" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "seq-macro" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_bytes" -version = "0.11.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" -dependencies = [ - "serde", - "serde_core", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "simba" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0b7840f121a46d63066ee7a99fc81dcabbc6105e437cae43528cea199b5a05f" -dependencies = [ - "approx", - "num-complex", - "num-traits", - "paste", - "wide", -] - -[[package]] -name = "simba" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "061507c94fc6ab4ba1c9a0305018408e312e17c041eb63bef8aa726fa33aceae" -dependencies = [ - "approx", - "num-complex", - "num-traits", - "paste", - "wide", -] - -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" - -[[package]] -name = "socket2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "statrs" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b35a062dbadac17a42e0fc64c27f419b25d6fae98572eb43c8814c9e873d7721" -dependencies = [ - "approx", - "lazy_static", - "nalgebra 0.29.0", - "num-traits", - "rand 0.8.8", -] - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - -[[package]] -name = "thiserror" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" -dependencies = [ - "thiserror-impl 2.0.21", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "thread_local" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "time" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" -dependencies = [ - "deranged", - "num-conv", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" - -[[package]] -name = "time-macros" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "tiny-keccak" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" -dependencies = [ - "crunchy", -] - -[[package]] -name = "tokio" -version = "1.54.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" -dependencies = [ - "bytes", - "libc", - "mio", - "parking_lot", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys", -] - -[[package]] -name = "tokio-macros" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" -dependencies = [ - "nu-ansi-term", - "sharded-slab", - "smallvec", - "thread_local", - "tracing-core", - "tracing-log", -] - -[[package]] -name = "twox-hash" -version = "2.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "unicode-segmentation" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" - -[[package]] -name = "uuid" -version = "1.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" -dependencies = [ - "getrandom 0.3.4", - "js-sys", - "serde", - "wasm-bindgen", -] - -[[package]] -name = "valuable" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.4+wasi-0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" -dependencies = [ - "cfg-if", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.10", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wide" -version = "0.7.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03" -dependencies = [ - "bytemuck", - "safe_arch", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "wyz" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" -dependencies = [ - "tap", -] - -[[package]] -name = "zerocopy" -version = "0.8.66" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.66" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" - -[[package]] -name = "zstd" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" -dependencies = [ - "zstd-safe", -] - -[[package]] -name = "zstd-safe" -version = "8.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" -dependencies = [ - "zstd-sys", -] - -[[package]] -name = "zstd-sys" -version = "2.2.0+zstd.1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" -dependencies = [ - "cc", - "pkg-config", -] diff --git a/Cargo.toml b/Cargo.toml deleted file mode 100644 index 0658ca13..00000000 --- a/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[workspace] -members = [ - "apps/stock/engine", - "tools/curate-etl", -] -resolver = "2" - -[workspace.package] -version = "0.1.0" -edition = "2021" -authors = ["Stock Bot Team"] -license = "MIT" -repository = "https://github.com/your-org/stock-bot" - -[workspace.dependencies] -# Common dependencies that can be shared across workspace members -tokio = { version = "1", features = ["full"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -chrono = { version = "0.4", features = ["serde"] } -uuid = { version = "1", features = ["v4", "serde"] } -tracing = "0.1" -thiserror = "1" -anyhow = "1" - -[profile.release] -lto = true -opt-level = 3 -codegen-units = 1 \ No newline at end of file diff --git a/DEVELOPMENT-ROADMAP.md b/DEVELOPMENT-ROADMAP.md new file mode 100644 index 00000000..2810b433 --- /dev/null +++ b/DEVELOPMENT-ROADMAP.md @@ -0,0 +1,377 @@ +# 📋 Stock Bot Development Roadmap + +*Last Updated: June 2025* + +## 🎯 Overview + +This document outlines the development plan for the Stock Bot platform, focusing on building a robust data pipeline from market data providers through processing layers to trading execution. The plan emphasizes establishing solid foundational layers before adding advanced features. + +## 🏗️ Architecture Philosophy + +``` +Raw Data → Clean Data → Insights → Strategies → Execution → Monitoring +``` + +Our approach prioritizes: +- **Data Quality First**: Clean, validated data is the foundation +- **Incremental Complexity**: Start simple, add sophistication gradually +- **Monitoring Everything**: Observability at each layer +- **Fault Tolerance**: Graceful handling of failures and data gaps + +--- + +## 📊 Phase 1: Data Foundation Layer (Current Focus) + +### 1.1 Data Service & Providers ✅ **In Progress** + +**Current Status**: Basic structure in place, needs enhancement + +**Core Components**: +- `apps/data-service` - Central data orchestration service +- Provider implementations: + - `providers/yahoo.provider.ts` ✅ Basic implementation + - `providers/quotemedia.provider.ts` ✅ Basic implementation + - `providers/proxy.provider.ts` ✅ Proxy/fallback logic + +**Immediate Tasks**: + +1. **Enhance Provider Reliability** + ```typescript + // libs/data-providers (NEW LIBRARY NEEDED) + interface DataProvider { + getName(): string; + getQuote(symbol: string): Promise; + getHistorical(symbol: string, period: TimePeriod): Promise; + isHealthy(): Promise; + getRateLimit(): RateLimitInfo; + } + ``` + +2. **Add Rate Limiting & Circuit Breakers** + - Implement in `libs/http` client + - Add provider-specific rate limits + - Circuit breaker pattern for failed providers + +3. **Data Validation Layer** + ```typescript + // libs/data-validation (NEW LIBRARY NEEDED) + - Price reasonableness checks + - Volume validation + - Timestamp validation + - Missing data detection + ``` + +4. **Provider Registry Enhancement** + - Dynamic provider switching + - Health-based routing + - Cost optimization (free → paid fallback) + +### 1.2 Raw Data Storage + +**Storage Strategy**: +- **QuestDB**: Real-time market data (OHLCV, quotes) +- **MongoDB**: Provider responses, metadata, configurations +- **PostgreSQL**: Processed/clean data, trading records + +**Schema Design**: +```sql +-- QuestDB Time-Series Tables +raw_quotes (timestamp, symbol, provider, bid, ask, last, volume) +raw_ohlcv (timestamp, symbol, provider, open, high, low, close, volume) +provider_health (timestamp, provider, latency, success_rate, error_rate) + +-- MongoDB Collections +provider_responses: { provider, symbol, timestamp, raw_response, status } +data_quality_metrics: { symbol, date, completeness, accuracy, issues[] } +``` + +**Immediate Implementation**: +1. Enhance `libs/questdb-client` with streaming inserts +2. Add data retention policies +3. Implement data compression strategies + +--- + +## 🧹 Phase 2: Data Processing & Quality Layer + +### 2.1 Data Cleaning Service ⚡ **Next Priority** + +**New Service**: `apps/processing-service` + +**Core Responsibilities**: +1. **Data Normalization** + - Standardize timestamps (UTC) + - Normalize price formats + - Handle split/dividend adjustments + +2. **Quality Checks** + - Outlier detection (price spikes, volume anomalies) + - Gap filling strategies + - Cross-provider validation + +3. **Data Enrichment** + - Calculate derived metrics (returns, volatility) + - Add technical indicators + - Market session classification + +**Library Enhancements Needed**: + +```typescript +// libs/data-frame (ENHANCE EXISTING) +class MarketDataFrame { + // Add time-series specific operations + fillGaps(strategy: GapFillStrategy): MarketDataFrame; + detectOutliers(method: OutlierMethod): OutlierReport; + normalize(): MarketDataFrame; + calculateReturns(period: number): MarketDataFrame; +} + +// libs/data-quality (NEW LIBRARY) +interface QualityMetrics { + completeness: number; + accuracy: number; + timeliness: number; + consistency: number; + issues: QualityIssue[]; +} +``` + +### 2.2 Technical Indicators Library + +**Enhance**: `libs/strategy-engine` or create `libs/technical-indicators` + +**Initial Indicators**: +- Moving averages (SMA, EMA, VWAP) +- Momentum (RSI, MACD, Stochastic) +- Volatility (Bollinger Bands, ATR) +- Volume (OBV, Volume Profile) + +```typescript +// Implementation approach +interface TechnicalIndicator { + name: string; + calculate(data: OHLCV[]): T[]; + getSignal(current: T, previous: T[]): Signal; +} +``` + +--- + +## 🧠 Phase 3: Analytics & Strategy Layer + +### 3.1 Strategy Engine Enhancement + +**Current**: Basic structure exists in `libs/strategy-engine` + +**Enhancements Needed**: + +1. **Strategy Framework** + ```typescript + abstract class TradingStrategy { + abstract analyze(data: MarketData): StrategySignal[]; + abstract getRiskParams(): RiskParameters; + backtest(historicalData: MarketData[]): BacktestResults; + } + ``` + +2. **Signal Generation** + - Entry/exit signals + - Position sizing recommendations + - Risk-adjusted scores + +3. **Strategy Types to Implement**: + - Mean reversion + - Momentum/trend following + - Statistical arbitrage + - Volume-based strategies + +### 3.2 Backtesting Engine + +**New Service**: Enhanced `apps/strategy-service` + +**Features**: +- Historical simulation +- Performance metrics calculation +- Risk analysis +- Strategy comparison + +--- + +## ⚡ Phase 4: Execution Layer + +### 4.1 Portfolio Management + +**Enhance**: `apps/portfolio-service` + +**Core Features**: +- Position tracking +- Risk monitoring +- P&L calculation +- Margin management + +### 4.2 Order Management + +**New Service**: `apps/order-service` + +**Responsibilities**: +- Order validation +- Execution routing +- Fill reporting +- Trade reconciliation + +### 4.3 Risk Management + +**New Library**: `libs/risk-engine` + +**Risk Controls**: +- Position limits +- Drawdown limits +- Correlation limits +- Volatility scaling + +--- + +## 📚 Library Improvements Roadmap + +### Immediate (Phase 1-2) + +1. **`libs/http`** ✅ **Current Priority** + - [ ] Rate limiting middleware + - [ ] Circuit breaker pattern + - [ ] Request/response caching + - [ ] Retry strategies with exponential backoff + +2. **`libs/questdb-client`** + - [ ] Streaming insert optimization + - [ ] Batch insert operations + - [ ] Connection pooling + - [ ] Query result caching + +3. **`libs/logger`** ✅ **Recently Updated** + - [x] Migrated to `getLogger()` pattern + - [ ] Performance metrics logging + - [ ] Structured trading event logging + +4. **`libs/data-frame`** + - [ ] Time-series operations + - [ ] Financial calculations + - [ ] Memory optimization for large datasets + +### Medium Term (Phase 3) + +5. **`libs/cache`** + - [ ] Market data caching strategies + - [ ] Cache warming for frequently accessed symbols + - [ ] Distributed caching support + +6. **`libs/config`** + - [ ] Strategy-specific configurations + - [ ] Dynamic configuration updates + - [ ] Environment-specific overrides + +### Long Term (Phase 4+) + +7. **`libs/vector-engine`** + - [ ] Market similarity analysis + - [ ] Pattern recognition + - [ ] Correlation analysis + +--- + +## 🎯 Immediate Next Steps (Next 2 Weeks) + +### Week 1: Data Provider Hardening +1. **Enhance HTTP Client** (`libs/http`) + - Implement rate limiting + - Add circuit breaker pattern + - Add comprehensive error handling + +2. **Provider Reliability** (`apps/data-service`) + - Add health checks for all providers + - Implement fallback logic + - Add provider performance monitoring + +3. **Data Validation** + - Create `libs/data-validation` + - Implement basic price/volume validation + - Add data quality metrics + +### Week 2: Processing Foundation +1. **Start Processing Service** (`apps/processing-service`) + - Basic data cleaning pipeline + - Outlier detection + - Gap filling strategies + +2. **QuestDB Optimization** (`libs/questdb-client`) + - Implement streaming inserts + - Add batch operations + - Optimize for time-series data + +3. **Technical Indicators** + - Start `libs/technical-indicators` + - Implement basic indicators (SMA, EMA, RSI) + +--- + +## 📊 Success Metrics + +### Phase 1 Completion Criteria +- [ ] 99.9% data provider uptime +- [ ] <500ms average data latency +- [ ] Zero data quality issues for major symbols +- [ ] All providers monitored and health-checked + +### Phase 2 Completion Criteria +- [ ] Automated data quality scoring +- [ ] Gap-free historical data for 100+ symbols +- [ ] Real-time technical indicator calculation +- [ ] Processing latency <100ms + +### Phase 3 Completion Criteria +- [ ] 5+ implemented trading strategies +- [ ] Comprehensive backtesting framework +- [ ] Performance analytics dashboard + +--- + +## 🚨 Risk Mitigation + +### Data Risks +- **Provider Failures**: Multi-provider fallback strategy +- **Data Quality**: Automated validation and alerting +- **Rate Limits**: Smart request distribution + +### Technical Risks +- **Scalability**: Horizontal scaling design +- **Latency**: Optimize critical paths early +- **Data Loss**: Comprehensive backup strategies + +### Operational Risks +- **Monitoring**: Full observability stack (Grafana, Loki, Prometheus) +- **Alerting**: Critical issue notifications +- **Documentation**: Keep architecture docs current + +--- + +## 💡 Innovation Opportunities + +### Machine Learning Integration +- Predictive models for data quality +- Anomaly detection in market data +- Strategy parameter optimization + +### Real-time Processing +- Stream processing with Kafka/Pulsar +- Event-driven architecture +- WebSocket data feeds + +### Advanced Analytics +- Market microstructure analysis +- Alternative data integration +- Cross-asset correlation analysis + +--- + +*This roadmap is a living document that will evolve as we learn and adapt. Focus remains on building solid foundations before adding complexity.* + +**Next Review**: End of June 2025 diff --git a/README.md b/README.md deleted file mode 100644 index 004c7e61..00000000 --- a/README.md +++ /dev/null @@ -1,758 +0,0 @@ -# Stock Bot - -Bun/TypeScript workspaces for market-data collection, processing, APIs, and a React dashboard, -with a Rust native trading engine. `apps/wcag-ada` is an independent project and is not part of -the root workspace checks. - -**New to the codebase? Start with [Understanding Stock Bot](docs/guide/README.md):** a -system map, a complete backtest walkthrough, TypeScript strategy authoring, and a -[function-by-function code tour](docs/guide/code-reading.md). For the target AI quant -research architecture and milestone roadmap (`M0`–`M5`), see the -[documentation index](docs/README.md) ([PLATFORM-PLAN.md](docs/PLATFORM-PLAN.md), -[MILESTONES.md](docs/MILESTONES.md), [DATA-CONTRACTS.md](docs/DATA-CONTRACTS.md), -[VALIDATION-AND-RIGOR.md](docs/VALIDATION-AND-RIGOR.md)). - -## Start the research workbench - -From the repository root, after installing dependencies and building: - -```sh -bun run infra:up -bun run dev:research -``` - -This starts the API on port 2003, orchestrator on 2004 and web app on 5173, with required -workspace builds. Infrastructure uses Docker Compose v2 and includes Dragonfly, PostgreSQL, -QuestDB and MongoDB. Keep the existing environment configuration; database credentials must -match the running stores. Configure the operator access token for browser login and the -API origin as described in the [web app guide](apps/stock/web-app/README.md). Startup does -not reset data, launch ingestion, or activate a paper/live account. Use `docker:start` as -an alias for `infra:up`; optional admin/monitoring services are separate commands. - -The obsolete `db:init`, `db:setup-ib` and `proxy` aliases were removed because their targets -no longer exist. Apply reviewed migrations explicitly; ordinary startup never initializes -or resets an existing database. - -## Current research workflow - -The web workbench is the primary interface: Strategies → Backtests → Experiments → -Research findings. New runs use retained inputs and the canonical Rust financial engine. -The supported default is one asset and one execution series, long-only, with explicit -cash, fee, slippage and risk policies. Previous results and legacy execution code remain -readable; the historical architecture sections below do not enable legacy execution for -new research. Multi-asset default policy and live trading remain gated. - -Built-in reviewed strategies use the trusted TypeScript callback path. Arbitrary retained -TypeScript candidates always use the isolated path, including after ordinary catalog -approval. Both send target intents to the same Rust engine. Neither the browser nor a -strategy implements account or fill accounting. `ownerBudget` is a strategy sizing input; -the engine's portfolio constraints are the actual financial limits. - -`services.orchestrator.backtesting.maxConcurrent` selects 1, 2 or 4 independent durable -workers (default 1). It parallelizes trials, never concurrent transitions within one account. - -### Prepare an isolated candidate - -After the normal repository build, explicitly build the trusted local sandbox image: - -```sh -bun run scripts/build-candidate-sandbox.ts -bun run scripts/package-candidate-strategy.ts metadata.json strategy.ts > candidate-package.json -``` - -The sandbox currently requires Linux x86_64, local Docker with cgroup v2, memory/swap/CPU/PID -limits, seccomp and AppArmor, plus `rustc` and the pinned Bun runtime. The image is built -from installed trusted runtime files without pulling a base image. The descriptor and -image ID are frozen into each request; a missing or different installation fails closed. -Preserve the matching image and descriptor when retaining runs for reproduction. - -`metadata.json` supplies `program`, `parameterSchema`, `source`, `entryExport` and -`execution: { "kind": "isolated-candidate/v1", "warmupBars": 0 }`. Set the warmup to the -maximum required by all intended parameter combinations. Use the -[retained package contract](libs/core/types/src/strategy-version.ts) and -[strategy decision API](libs/research/src/strategy-api.ts). -The entry export is a synchronous factory receiving the retained selection and returning -a target-mode strategy with explicit JSON state. The CLI transpiles self-contained -TypeScript inside isolation; it does not evaluate the source or install dependencies. - -Upload the package on the strategy page, validate parameters, then select its immutable -version in a saved backtest or experiment. Publication never starts a run. Candidates -receive only published observation/context prefixes, with no host filesystem, network, -credentials, broker or database access. The frozen sandbox policy limits each attempt to -512 MiB, one CPU, 64 PIDs and at most 300 seconds; a shorter agent deadline wins. Author -warmup declarations and seeded helpers do not prove that arbitrary JavaScript is free of -leakage or nondeterminism. Inspect diagnostics and reproduce the actual result. - -### Run an AI research cycle - -An operator creates a research-only agent on the Research agents page, grants the project -and saved template, explicitly allows its own candidates, and sets bounded job budgets. -Give that research token to the client, never an operator or brokerage credential. - -```sh -RESEARCH_API_ORIGIN=http://127.0.0.1:2003 RESEARCH_API_TOKEN=sb-research.… \ - bun run scripts/examples/research-cycle.ts --plan prepared-plan.json --receipts new-receipts.jsonl -``` - -[ResearchCyclePlan](scripts/examples/research-cycle.ts) defines the input. Supply prepared -packages, parameters, bounded grids, chronological windows and cost scenarios before -reading results. The example runs training first, freezes the server-selected candidate, -then evaluates holdouts and costs, retaining failed trials and exact evidence citations. -Findings remain explicitly AI-authored and unvalidated narratives. Use -[ResearchClient](scripts/research-client.ts) for individual APIs, including walk-forward. - -Use `ResearchClient.canonicalRunResult(runId)` to inspect a completed canonical run's -full retained request, native fills, positions, final risk state, analytics and provenance. -The client and API share result validation; financial decimal strings and unavailable -metrics are preserved. Missing results remain read errors so callers can inspect the -saved trial status and diagnostics. - -Read the original market data with `ResearchClient.canonicalDataset(result.request.datasetHash)`. -The client verifies the complete v2 snapshot and its hash before returning frozen bars -and metadata. Research credentials can read exact known-hash exports; dataset discovery, -provider preparation and data writes use the operator workflow. Use the predeclared training -snapshot for exploration and preserve untouched holdouts until evaluation. Candidate -callbacks continue to receive published prefixes through their isolated runtime. - -To save a comparison across studies, call `ResearchClient.saveFinding` with `source: null` -or omit `source`. Include a nonempty list of canonical metric references with each run's -exact strategy-version ID. The API resolves their values from retained completed runs; -the finding remains AI-authored and unvalidated. A supplied experiment/report source -instead binds the finding to that source and its membership checks. Combining references -does not establish that the runs are comparable or create a sealed validation report. - -Use `ResearchClient.artifact(artifactId)` to reopen a saved finding or note, and -`ResearchClient.artifactRevisions(artifactId)` to read its immutable history. Select the -revision whose `id` matches the one retained in your research journal; stop if it is absent. -The latest revision can contain a later human interpretation. These authenticated reads -preserve actual authorship, evidence units, unavailable metrics and legacy qualifications. - -Reopen the original research question with `ResearchClient.hypothesis(hypothesisId)` and -`ResearchClient.hypothesisRevisions(hypothesisId)`. Match the saved hypothesis revision ID -from your journal or finding, and stop if it is absent. A later human edit can change the -latest proposition and validation criteria; archived questions and their original revisions -remain readable. These reads preserve actual authorship and do not validate a hypothesis. - -The receipt journal is mandatory and created exclusively. On interruption, inspect its -intents and accepted IDs, reopen durable resources, and retry only the exact idempotent -request. Do not blindly restart a cycle: hypothesis, family and finding creation do not -have replay keys. The client cannot promote or activate paper/live trading. - -Human paper promotion uses the separate `/paper` workflow and a configured, initially -halted paper host. See [paper setup and evidence requirements](docs/development/architecture/research-product.md). -Creating a deployment is distinct from binding and activating it; development tests use -disposable accounts only. - -## Build and verify - -Use Bun 1.2.17, Node.js 18 or newer, and a Rust toolchain with a native linker. CI uses Rust -1.88. Building and the tooling/contract/integration checks do not require running databases or provider -credentials. - -```sh -bun install --frozen-lockfile -bun run build -bun run check -``` - -The root build selects every buildable leaf workspace, including all stock services and the -native engine. `bun run build --dry=json` shows the actual Turbo task plan. - -| Command | Scope | -| --------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `bun run build:libs` | Build shared libraries in dependency order | -| `bun run build --clean` | Force every workspace build without cached results | -| `bun run typecheck` | Check library, stock application, and tool source directly | -| `bun run test:contracts` | Compile positive and negative service-contract assertions | -| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure | -| `bun run test:utils` | Test HTTP/date/proxy helpers and their handler HTTP consumer without infrastructure | -| `bun run test:calculations` | Test shared math, OHLCV transforms, legacy capability preservation and research snapshots | -| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine | -| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed | -| `bun run check` | Run build, type checking, contracts, tooling, utilities, calculations, integration, native tests, and lint | - -`check` exits nonzero if any gate fails. Type/lint errors are not suppressed or baselined. -The larger existing `bun run test` suite is separate: -some tests need databases, Redis, browsers, or native-engine fixes. - -Native builds generate `apps/stock/engine/dist/engine.node` and `dist/index.d.ts`. The public -ESM/CommonJS loaders and declaration facade use those generated artifacts. Rebuild after -changing Rust APIs. TensorFlow is loaded only when starting the optional ML strategy. -Its TypeScript dependency is present for checking; using ML also requires installing its -platform-specific native binding. Dependency install scripts were not enabled for verification. - -## Shared calculation and utility boundaries - -`@stock-bot/calculations` owns pure reusable math for strategies, data processing and -feature engineering. Its supported subpaths expose reviewed returns, indicators, OHLCV -transforms and the previously tested orchestrator analytics/window math. The orchestrator -now consumes that library; no database, native binding, HTTP or application service is -required to import it. Existing strategy checkpoint versions and financial execution -behavior are unchanged by this relocation. See -[the calculation contract](libs/calculations/README.md) for supported units, undefined -values, alignment and validation rules. - -`@stock-bot/utils` retains HTTP/user-agent, proxy/sleep and validated UTC date/weekday -helpers through explicit capability subpaths. Deprecated `dateUtils` names are aliases, -not an exchange holiday/session calendar. Assertions belong to `@stock-bot/invariants`, -and domain types to `@stock-bot/types`. The coverage CLI no longer declares an unused -utility dependency, and unused `simple-statistics` is removed. - -[The utility contract](libs/utils/README.md) documents the general HTTP and user-agent -helpers. Architecture tests enforce the ownership and dependency boundaries without -forbidding useful shared domain libraries. - -## Service contracts - -`@stock-bot/types` contains independent domain, job, and handler types. -`@stock-bot/services` composes service capabilities from the public APIs exported by the -owning adapters. It uses type-only imports and does not initialize connections. - -```ts -import type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; -import type { ExecutionContext } from '@stock-bot/types'; -``` - -The DI and handler packages re-export `IServiceContainer` for existing consumers. Queue -managers and individual queues are separate capabilities: obtain queues through -`container.queueManager`, submit with `queue.add`, and await results with `queue.waitForJob`. -Use `getFullQueueName(service, handler)` when addressing another service's queue. - -Use `requireServices(container, 'mongodb', 'queueManager')` at consumer boundaries when -those capabilities are required. Missing/disabled adapters fail explicitly before work begins. -`@stock-bot/invariants` provides small, dependency-free checks for required values and -indexed array reads; browser code can use it without importing server utilities. - -Handler initializers receive their scanner/registry explicitly through the DI application -initialization context. WebSocket connections and completion timers belong to the socket -handler and are released on close/shutdown. - -## Orchestrator boundaries and extension points - -Keep runtime composition in `container.ts`; domain code receives explicit capabilities, -not the application service container: - -Backtest engines, `StrategyManager`, `ModeManager`, and `MarketDataService` receive their -required collaborators directly. The native adapter uses the composed storage instance, -never a fallback it constructs itself. Composition binds strategy factories to the current -mode and provides the feed's strategy-drain callback; factories still receive the existing -`{ modeManager, execution }` contract. `services.custom` remains an HTTP/job/lifecycle adapter -lookup surface, not an internal dependency registry for these components. Direct constructor -callers must supply the explicit dependencies; the strategy manager no longer caches or -exposes the current trading engine, which is owned by `ModeManager`. - -- `contracts/` holds runtime validation schemas. Contracts and the native worker protocol - cannot load storage, native engines, or server adapters. -- `execution/model.ts` owns accounting/risk rules; `execution/repository.ts` is the storage - port, independent of either implementation. -- `SimulationExecution` applies order admission, matching and accounting inside the caller's - transaction. It does not open transactions or publish notifications. -- `StrategyRecovery` owns decision scopes, checkpoint/cursor commits and outbox replay. - Its typed runtime port preserves the gateway's transaction and serialization boundaries. -- `ExecutionService` composes those components, owns lifecycle/market admission, selects the - repository, and publishes only after commit. HTTP and strategies continue using this gateway. -- `StrategyManager` owns lifecycle/delivery; `StrategyRegistry` owns strategy factories and - aliases. Add a lazy factory to `createBuiltinStrategyRegistry()`, or provide a custom - `strategyRegistry` to `registerOrchestratorServices`. No manager switch needs updating. - Keep persisted aliases stable; a custom registry must also be supplied on restart. - -Supported TypeScript implementations live in `strategies/builtin/`: `SmaCrossoverStrategy` -and `MeanReversionStrategy`. Optional ML research lives in `strategies/experimental/`, still -lazy-loaded and unavailable for paper execution. The unregistered strategy variants and their -private position/risk framework have been removed; `ExecutionService` remains the financial -authority. File/class relocation preserves the existing aliases and v2 checkpoint versions. -Use the [strategy development guide](docs/guide/strategy-development.md) -for the supported lifecycle and a type-checked, integration-tested runner example. Removed -internal deep imports must migrate; their source remains recoverable in Git history. - -New paper strategies must provide a complete versioned checkpoint contract and recovery -tests. Registering a factory does not bypass risk checks or the durable-checkpoint requirement. -The experimental ML strategy remains unavailable for paper execution. - -Architecture tests run in `bun run check`, checking runtime dependency cycles and the -contract/domain/adapter boundaries. - -### Strategy parameters and indicator math - -`contracts/strategy-names.ts` owns built-in aliases; spaces, underscores and hyphens normalize -to the same identity. `contracts/strategies.ts` owns backend-specific parameter schemas, and -`backtest/strategy-plan.ts` applies shared defaults followed by per-strategy overrides for -both backends. Disabled entries do not run or consume TypeScript allocation. Invalid built-in -parameters fail before historical input loading; unknown/unsupported keys, numeric strings, -fractional periods and nonfinite values are rejected rather than ignored or truncated. -Custom TypeScript factories retain their own parameter contracts and extension fields. - -Periods are integer bars bounded by 10000, with `fastPeriod < slowPeriod` for SMA. Both SMA -backends default to 5/15 and accept an explicit `quantity` in shares (1e-8 through 1e9). -Without `quantity`, TypeScript SMA uses `positionFraction` (default 0.1 of account equity), -while native SMA uses 100 shares. Native mean reversion, momentum and pairs retain their -`positionSize` parameter in **shares**, not an equity fraction. TypeScript mean reversion -accepts configurable lookback/trend/RSI windows, entry/exit thresholds and notional-volume -filter; its optional `quantity` is also shares. Do not transfer backend-only parameters blindly. - -`@stock-bot/calculations/indicators` shares slice-free trailing mean, population deviation -and crossover calculations across TypeScript strategies. A crossover requires `slowPeriod + 1` -bars, including a complete previous window; missing warm-up is not a synthetic zero average. -Tests compare the scalar math with real Rust batch/incremental indicators and exercise -configured SMA fills in both backends. This is not full algorithm/result parity: entry/exit -and RSI rules differ, and native backtests force liquidation at the end while TypeScript -backtests retain open positions. Corrected warm-up and previously ignored settings can change -historical results. - -### TypeScript backtest composition - -`BacktestEngine` coordinates fresh components for each run: - -- `BacktestPlayback` owns the input cursor, pacing and interruptible pause/resume/stop. - Frozen bars are consumed in order without a second event array or queue shifting; - unlimited playback periodically yields so cancellation and lease heartbeats can run. -- `BacktestMarket` owns seeded market projection and per-symbol microstructure defaults. - It cannot submit orders; financial state still belongs to the execution ledger. -- `BacktestReport` records ledger equity and builds a detached completed snapshot. - `report-format.ts` formats that snapshot without re-reading the engine or adding trades. - -Overlapping runs fail before state changes. Cancellation raises `BacktestCancelledError`; -the runner records cancellation without persisting a partial successful result. Pending -historical reads cannot resume a cancelled run, and stop wakes paused/paced playback. -Arbitrary custom strategy callbacks are still cooperative, not forcibly isolated. - -Equity and final position valuations come from `ExecutionService`, not a best-effort native -P&L projection. Missing ledger state fails; zero/negative equity is never replaced with -starting capital. Drawdown duration uses simulated time. Month-end returns use UTC boundaries -and the preceding month-end balance (initial capital for the first month); percentage returns -with a nonpositive baseline are omitted. These corrections can change historical metrics. - -`exportResults()` is available after successful completion until the next run begins. -Repeated JSON/CSV/HTML exports retain the finished equity and trade count; exports cannot -mutate analysis. Charts and quality observations group frozen bars in one pass, but datasets -and detailed equity history still reside in memory; this is not a streaming backtest engine. - -## Analytics correctness and availability - -`orchestrator/src/analytics/{equity,return-statistics,trade-statistics,performance}.ts` -contains pure shared math. `PerformanceAnalyzer` is a detached, cached compatibility facade; -`BacktestReport` consumes that same analysis instead of recalculating daily returns, drawdowns -and risk statistics. Core returns and risk magnitudes are fractions. The legacy direct-backend -and report-summary percentage-point fields are converted only at the facade; the runner's -persisted/public `BacktestRunResult` still uses fractions. Risk statistics no longer apply -volatility/VaR calculations directly to percentage-point returns (the former 100× scaling bug). - -Conventions are explicit and covered by golden fixtures: - -- UTC daily/month-end observations use the final value in each period. The first period uses - initial capital, so its gain/loss is not discarded. Nonpositive subsequent denominators are - omitted rather than replaced; same-timestamp observations use the last value. -- CAGR uses observed elapsed calendar time (365 days/year), and is `null` for zero elapsed - time, nonpositive ending equity or an unrepresentable result. Total losses and drawdowns - beyond 100% remain valid observations; no opening balance is invented. -- Volatility uses sample standard deviation and 252 observed daily periods/year. Sharpe uses - arithmetic daily excess returns against a 2% annual reference rate divided by 252, not CAGR - divided by volatility. See [Sharpe's definition](https://web.stanford.edu/~wfsharpe/art/sr/sr.htm). -- Sortino uses full-series downside RMS relative to that daily reference target, not the - standard deviation of only negative returns. The denominator includes every observed return; - see [PerformanceAnalytics' downside-deviation conventions](https://search.r-project.org/CRAN/refmans/PerformanceAnalytics/html/DownsideDeviation.html). -- Historical VaR/CVaR are nonnegative loss magnitudes from the worst empirical tail. The 95% - tail requires at least 20 returns; the 99% tail requires 100. These are historical statistics, - not forecasts. Sparse observed dates are not an exchange-calendar completeness guarantee. -- Drawdown periods have independent peak-to-trough depth, recover on equality with the peak, - and measure calendar days from the first below-peak observation to recovery or the observed - end. Ongoing periods are explicit; neither duration nor depth comes from another period. -- Undefined ratios and insufficient-sample statistics are `null`, not zero or infinity. - Profit factor is `null` with no losses; breakeven trades reset win/loss streaks. Empty trade - series retain zero trade count/win rate as a convention. UI/text ratios display unavailable - values as “N/A” or “-”; JSON preserves `null`. The old leverage field remains a compatibility - heuristic, not an optimizer or trading recommendation. - -Corrected analytics can change new-run results. Existing saved rows are not recalculated and -no database migration/reset is performed. Native trading algorithms and engine-specific -supplemental statistics are not silently redefined by this TypeScript math refactor. - -Run `bun run check` for TypeScript/native checks and analytics regression fixtures. - -## Backtest data integrity - -Historical storage no longer invents prices when a database is unavailable. Configure a -historical store, or explicitly set `services.orchestrator.backtesting.allowSyntheticData` -for offline demos, with `syntheticSeed` for repeatability. Synthetic data is disabled by -default and must not be used to assess trading performance. MongoDB's normalized EOD -store currently supports daily bars only; intraday requests require QuestDB. - -The integration test uses an in-memory persistence transport and the real storage/native -engine path. It checks idempotent ingestion, invalid-price rejection, repeatable trades, -and explicit failures for missing data or unsupported strategies. No live provider or broker -is contacted. Native SMA and MACD regressions are covered by the repository checks. - -Coverage reports contain measured LCOV data only. Missing coverage or an empty package -selection fails the coverage command instead of producing an estimated score. - -## Historical input identity and reproducibility - -Backtest `symbols` are exchange-qualified IDs such as `AAPL.US` or `BRK.B.US`, using -the existing EOD provider exchange namespace (not a guessed venue MIC). Ticker-only -definitions remain readable but must be explicitly updated before a new run. MongoDB -history reads match the qualified `eodSearchCode` and verify each returned identity; -QuestDB `bars_.symbol` must contain the same qualified ID. No ticker fallback, -automatic legacy-history rewrite, or cross-provider fallback is performed. -Provider namespace (`providerExchange`, also encoded in the ID) is distinct from the -source's `exchange` venue metadata. Older rows with a valid qualified key remain readable -without rewriting that metadata. - -`dataPolicy` explicitly describes prices and timestamps: - -- `adjustment: 'raw'` is the default; no corporate-action accounting is implied. -- `adjustment: 'provider-adjusted'` scales **all OHLC/VWAP prices** by - `adjustedClose / close`. Missing/nonpositive provider factors fail the run. This is - the provider's combined split/dividend adjustment, not a split-only or point-in-time - total-return model. Reported volume is unchanged; no extra dividend cash is credited. -- Daily bars use `timestamp: 'utc-session-date'`: UTC-midnight session labels, not - exchange close instants. Daily range boundaries must be UTC midnight. Intraday bars - use `timestamp: 'utc-instant'` with an explicit timezone. Ranges are `[start, end)`. -- Invalid prices, duplicate timestamps, mixed identities, or missing requested listings - fail; prices are never interpolated or silently repaired. Market holidays are not - synthesized, and exchange-calendar/session completeness is not yet verified. - -Apply additive migration `database/postgres/init/12-historical-datasets.sql` via the -web API migration runner before starting a new backtest. The first execution attempt -validates and content-hashes the actual input bars and provenance, then atomically stores -them in `backtest_datasets` and pins `runs.dataset_hash` **before executing any bar**. -Recovered attempts reuse that snapshot, never revised provider data. Both execution -backends consume the same normalized, deterministically ordered bars with no second -corporate-action transformation. The TypeScript simulator's pseudo-random sequence is -seeded from the dataset hash; native same-timestamp seeks retain every listing. - -The canonical result records the manifest in `config.dataset`: SHA-256 hash, listing -identities, range, interval, adjustment/timestamp/volume policies, source normalization -revision, and bar count. Replay through the runner by supplying `datasetHash` (or put it -in a V2 definition's `config`); the range, listings, interval and policy must match. -Missing, corrupted or incompatible snapshots fail instead of falling back to provider -history. Runs capture data at execution preparation, **not HTTP acceptance time**. -Reproducibility assumes the same engine/strategy code and configuration; the snapshot -is not an engine binary archive or a point-in-time constituent universe. Direct backend -calls can load data for diagnostics, but durable replay/persistence requires the runner. -Dataset preparation has no application-level instrument, bar-count or payload-size caps. -Internal handoffs reuse deeply frozen validated inputs; restored snapshots are always -content-checked. Existing v1 hashes and replay identities are unchanged. Snapshots remain -JSONB and load in memory. See [dataset preparation](docs/backtest-datasets.md). - -## Simulation order execution - -### Durable strategy recovery - -Apply additive migration `13-strategy-recovery.sql` through the web API before starting -the orchestrator. Paper startup restores registered strategy configurations and their -checkpoints before connecting the feed. No running database is migrated by the tests. - -The recovery path has four checked transaction boundaries: - -1. Validate and durably admit a uniquely identified market payload into - `simulation_market_inputs`; retries cannot append a second input or change its payload. -2. Apply the next input's quote/account changes and resting-order fills, journal the - execution notifications and market payload, and mark the input applied atomically. -3. Restore each strategy's latest checkpoint under the account row lock, evaluate its - next journal record, then commit indicator/base state, cursor, and order intents together. -4. Dispatch an intent through the ordinary risk/idempotency gateway; order/fill accounting, - its execution journal notification, and the intent's dispatched status commit together. - -New inputs can queue during an outage or strategy error. Later inputs and new manual -orders cannot advance past unfinished enabled-strategy delivery or pending intents. -Idempotent order retries still return their committed report; explicit cancellations remain -available. Execution/fill notifications have their own durable cursor delivery, not a -volatile callback. Strategy reads use the journal's as-of account view, not future quotes. -Competing service instances always restore the locked checkpoint before evaluating a step. -The manager retries recovery every second without requiring another feed tick, and -`GET /api/recovery` exposes pending work and per-strategy cursor lag behind normal API auth. - -SMA (both implementations) and mean reversion have explicit versioned indicator contracts. -Base checkpoints include positions, pending orders, performance and a bounded recent-fill -cache; the durable cursor, not the cache size, guarantees delivery deduplication. A changed -configuration or checkpoint/implementation version requires an explicit new strategy ID; -there is no implicit state reset or best-effort schema coercion. Developers must bump the -strategy version when its state or decision semantics change. Custom paper strategies must -implement and validate their complete finite-JSON checkpoint. Uncheckpointed/experimental -ML paper strategies fail **before** model startup: asynchronous model training and weights -do not yet have a replay-safe artifact contract. Run-local backtests can still use explicitly -unversioned experimental strategies, without claiming restart recovery for their custom state. - -The configurable SMA and mean-reversion implementations now use checkpoint version **v2**. -They do not resume v1 registrations. Before deploying against an existing paper account, -explicitly pause the affected v1 registrations using the compatible runtime, review pending -intents/open orders, and register new strategy IDs with validated v2 parameters and fresh -indicator warm-up. Enabled v1 registrations block recovery even if a new ID is also supplied. -Pausing does not cancel committed work. No upgrade step rewrites checkpoints, resets account -balances or deletes historical registrations; tests do not modify running development accounts. - -Strategy evaluation must be bounded and deterministic: no fire-and-forget state mutation, -wall-clock/random decisions, broker calls, model training or external I/O in callbacks. -Repository I/O/direct submissions from a callback fail closed; use the as-of account view -and captured order intents. These callbacks run under an account lock, so an unbounded -custom callback stalls that account until its owner exits; isolation/time limits for arbitrary -third-party code are not provided here. Noncritical signal/UI observers run after commit; -their failure cannot erase a financial intent, but those observations are not a durable bus. - -Graceful shutdown suspends strategies without cancelling durable orders or erasing indicators. -`StrategyManager.disableStrategy` pauses **new decisions**, preserving already committed -intents and open orders; it is not an emergency order-cancel switch. Disabled-period market -records do not become retroactive signals on re-enable. To cancel, use the explicit order -API (or an intentional strategy stop). If a recovered paper quote has aged out, its indicator -state is recovered but it cannot generate fabricated historical fills: resulting stale-price -orders are rejected by the normal gateway. - -Legacy fingerprints without payloads are preserved, not invented into replay history. -New registrations begin at the current journal boundary with the existing financial -projection; pre-migration indicators/performance cannot be reconstructed automatically. -This guarantees recovery of **admitted** inputs, not delivery from an upstream socket before -admission. A provider replay/acknowledgement protocol is still required for that boundary. -Journal/input/history tables currently retain JSONB payloads and as-of account snapshots; -configure an archival/retention design before high-volume production use. Do not delete -history still needed by a paused strategy's cursor. - -`ExecutionService` is the runtime order gateway for REST, Socket.IO (when enabled), and -TypeScript strategies. `PaperTradingManager` is a compatibility facade, not a separate -simulator. Strategies consume only the ordered batch stream; individual-event broadcasts -cannot submit the same order a second time. Each event is delivered serially, including -awaited order/fill notifications before the next event. The TypeScript backtest uses this -same gateway with an explicit run-local repository; it does not write the paper ledger. -The isolated native backtest retains its own Rust loop and enforces its configured risk -limits before submission. Its projected notional and accounting rules have golden tests. - -Paper execution requires PostgreSQL and additive migration -`database/postgres/init/11-simulation-execution-ledger.sql` (included in the web API migration -allowlist). Start the migrated web API before the orchestrator. New `simulation_accounts`, -`simulation_orders`, `simulation_fills`, and `simulation_events` tables are account-scoped. -The account snapshot (cash, positions, quotes, strategy quantities, risk state), order -reports, and uniquely identified fills commit on one checked-out connection under an -account row lock. No acceptance or fill notification is published before commit. -The snapshot is a bounded-by-instruments projection; normalized order/fill/event history is -kept separately. Historical rows in the old `orders`/`fills`/`positions` tables are preserved -but are **not automatically adopted into the new ledger**. Reconcile legacy paper holdings -explicitly before continuing an old account; this migration never infers an opening balance. -Unused direct financial writers were removed from `StorageService`. - -Paper configuration accepts `accountId` (default `paper-default`), `riskLimits`, `commission`, -`slippage`, and `maxQuoteAgeMs` (default 60000). Restarting the same account restores cash, -positions, per-strategy quantities, consumed quote liquidity, and unfilled orders; it never -resets capital. A different starting capital requires an explicit new account ID. Strategy -indicator state is checkpointed for supported strategies; a new strategy still needs its -normal warm-up. Pending -orders retain the commission/slippage policy under which they were accepted. - -Order HTTP/Socket.IO submissions require a nonempty `clientOrderId`. Retrying an identical -request returns the existing order; reuse with different fields is a conflict (HTTP 409). -Strategies derive stable IDs from the strategy and source event. Supply a stable, unique -`eventId` on market data; identical replay is ignored, conflicting reuse is rejected. Without -an ID, a deterministic hash of the canonical event is used (identical same-timestamp payloads -are indistinguishable). Admitted source events, strategy delivery and financial notifications -now have durable recovery as described above; this is not a real-broker exactly-once guarantee. - -The deterministic simulator supports market/limit orders and DAY/GTC/IOC/FOK. Quote depth -is consumed across orders, partial fills await fresh events, and limit orders never fill -through their limit. DAY expiry is UTC/event-driven, not exchange-calendar-aware. Missing, -stale, future, or invalid quotes cannot produce fills; unsupported stop orders are rejected. -Backtests use completed-bar close/volume as a documented simulation input, not exchange -execution guarantees. No random slippage or fabricated broker acknowledgements are used. - -Position/order limits are shares; symbol/gross exposure and daily loss are account-currency -amounts. Checks include projected positions, pending-order reservations, current marks, and -an unlevered capital budget. Risk-reducing closes remain possible after a loss-limit breach. -Daily loss rolls at UTC midnight, and each fill contributes its **delta**, never cumulative -realized P&L. Fees are charged once, cash/equity include signed position value, and partial -closes/reversals allocate entry/exit commissions proportionally. The paper model uses decimal -arithmetic rounded to eight decimal places; it is single-currency and does not model FX, -borrowing, interest, corporate actions, or exchange-specific settlement. - -Live mode, broker/exchange routing, and direct native `TradingEngine.submitOrder` are -explicitly unsupported. They fail closed instead of reporting mock acceptance. Position, -P&L, and risk endpoints read the gateway ledger rather than native paper projections. -This milestone does not connect a broker, place real orders, or make the project live-ready. - -## Backtest execution workflow - -The orchestrator's `BacktestRunner` is the application boundary for both HTTP and decorated -jobs. It validates the request, claims a run, executes the configured native or TypeScript -backend, normalizes the result, and commits the result and terminal status in one transaction. -Completion events are published only after that commit. Progress cannot revive a terminal -run, duplicate claims are rejected, and unsupported controls do not change persisted state. - -`@stock-bot/stock-config/backtest` owns the pure execution request schema, parsing and -defaults used by API definition snapshots, the runner and both backends. The subpath -loads no configuration manager or infrastructure. API date labels are translated to UTC -before execution; direct execution requests keep their existing full-ISO timestamp shape. -Strategy-specific parameter validation remains with each execution backend. Invalid -execution settings now fail before a definition/run write rather than being queued for -later rejection. Existing schema imports from the orchestrator remain compatibility exports. - -`BacktestExecutionSettingsSchema` also identifies execution-only fields in legacy mixed -`config` bags. After shared defaults and per-strategy overrides are merged, the common -planner removes those fields before validating built-in parameters. For example, -`dataFrequency` selects run input, not an indicator parameter; a per-strategy copy cannot -override the run. Unknown parameter keys still fail validation. Custom TypeScript factories -retain their existing extension-field contract. Original mixed configs remain unchanged in -request snapshots and result provenance, including replay; no saved configuration migration -or checkpoint-version change is required. - -`@stock-bot/types` exports the shared `BacktestRunResult` used by the runner, API, and UI. -Return, win-rate, drawdown, and chart-analytics percentages use fractions (`0.10` means 10%). -Trade records identify their granularity with `kind: 'fill' | 'closed'`; `totalTrades` counts -completed round trips. Undefined ratios remain `null`. Engine-specific supplemental metrics -retain their documented backend meaning. - -The web API owns backtest definitions and pending-run creation; the orchestrator owns -execution state and result writes. V1 is a compatibility facade over V2, not a second SQL -schema or execution path. Strategy parameters and exact run configuration are preserved. -All historical readers delegate to the same storage policy; simulated fills do not enter -the trading ledger. Shared adapters are closed by DI, not by a backtest mode transition. - -Deployment requires the additive migrations -`database/postgres/init/09-backtest-run-contract.sql` and `10-durable-backtest-dispatch.sql`, -after the existing runs migration. The web API's migration allowlist includes both. -The first adds configuration/provenance columns and -a unique result-per-run index without deleting history. Existing duplicate result rows must -be reconciled before applying that index. Historical rows without snapshots remain readable -and are explicitly marked `legacy`; their configuration is reconstructed from the definition. -New executions require PostgreSQL; there is no implicit in-memory production repository. - -Stored-result compatibility conversion lives in the web API's pure `backtest-result.ts` -mapper, separate from SQL and run control. Current snapshots are returned without unit -conversion; pre-contract native/TypeScript rows retain their existing legacy unit rules. -Reading a result never rewrites the stored history or recalculates its metrics. - -Native execution uses a disposable **worker process**, not the HTTP thread. A small -`BacktestExecutionEngine` port separates the runner from both implementations. The parent -owns storage reads and persistence; only serializable configuration, bars, progress, and -results cross IPC. One native worker runs at a time per orchestrator instance; additional -requests receive a conflict rather than spawning unbounded workers. The existing -`maxConcurrent` setting does not enable parallel runs through this serialized runner. - -`services.orchestrator.backtesting.executionTimeoutMs` defaults to 300000 (five minutes) -and covers historical reads, worker startup, and native execution, not result persistence. -Cancellation and deadlines kill and reap the worker even during a synchronous Rust call. -A forced cancellation commits `cancelled` without a result row or fabricated partial metrics; -the original execution request returns HTTP 409 with `status: 'cancelled'`, and `/stop` -acknowledges only after that status is persisted. SSE publishes a terminal `cancelled` event. -Native pause/resume and speed controls remain explicitly unsupported. Native progress is -stage-level, not an invented percentage inside Rust's synchronous loop. Shutdown handles -SIGINT and SIGTERM, stops the worker, and settles its run before service cleanup. - -The orchestrator build emits **both** `dist/index.js` and `dist/native-worker.js`; deploy -them together with the external `@stock-bot/engine` package/native binary. The worker does -not require source TypeScript in production. Process isolation is intentional: terminating -a thread cannot guarantee interruption or contain a native process crash. - -The integration suite covers both real engines, REST/job parity, V1/V2 dispatch and result -reads, missing data, duplicate/concurrent requests, failed persistence/rollback, controls, -responsive requests/streams, worker crashes, deadlines, cancellation, and cleanup. SQL tests -use an in-process PostgreSQL emulator and the real transaction manager, not a live database. - -### Durable dispatch and recovery - -`POST /api/v2/backtests/:id/runs` returns **202** with a pending run ID and a `Location` -header. In one PostgreSQL transaction it stores the run, its immutable execution request, -and a `backtest_dispatch` intent. No Redis/HTTP call is needed to accept the run. Editing -a definition later does not change an accepted run. The V1 facade uses the same workflow. -The orchestrator's direct synchronous REST execution routes remain compatibility endpoints. - -The web API runs a producer-only dispatcher (zero workers) every five seconds. It reserves -due intents with `FOR UPDATE SKIP LOCKED` and publishes identity-only notifications to the -existing `{orchestrator_orchestrator}` queue. Stable job IDs deduplicate outstanding jobs; -pending intents are republished every 30 seconds, including after a lost Redis job or a -publisher restart. Redis outages leave accepted runs pending; they do not falsely fail them. -The queue clients honor explicit Redis endpoints and reconnect after transient outages. - -Each orchestrator consumes one job at a time. It atomically claims a pending run with a new -attempt UUID and a 30-second PostgreSQL-clock lease, renewed every five seconds. Progress, -controls, failure, cancellation, and terminal result writes are fenced by that attempt and -an unexpired lease. A lost heartbeat stops the local execution and leaves recovery to the -dispatcher. Expired owners are retried from their saved request, up to three execution -attempts; exhaustion becomes `failed`. Terminal redelivery is acknowledged without rerunning. -Computation is at-least-once, not exactly-once; only an owned result can commit, atomically -with terminal status, and the unique result-per-run constraint remains the final guard. -Recovery also depends on BullMQ detecting stalled jobs and the API dispatcher being available. - -Cancellation is durable: queued runs become `cancelled` before a claim; active runs record -`cancel_requested` for their owner to observe, stop, and acknowledge. The V2 cancel endpoint -returns **202**, not a claim that execution already stopped. A cancelled abandoned lease -becomes `cancelled`, without a result. The dashboard keeps polling until persisted terminal -state; WebSocket updates are read from committed SQL state, not an in-memory dispatch request. -Native pause/resume/speed remain unsupported; those compatibility controls still require -the HTTP request to reach the owning instance. - -Before applying migration 10, **stop all older orchestrators**, start the migrated web API, -then start lease-aware orchestrators. Legacy pending runs receive a one-time snapshot of -their current definition; legacy active runs with no owner token are marked failed rather -than pretending they are recoverable. Existing results are preserved. Infrastructure should -supervise the orchestrator process tree: SIGKILL of a parent cannot guarantee reaping a child -blocked in native code, though a stale child cannot persist a result through the fenced parent. -No migration or restart is performed against your existing local databases by the tests. - -## HTTP access and secrets - -HTTP services now fail closed unless server-side access tokens are configured. Use the -root `.env` (`.env.example` documents the settings) and set independent `STOCK_BOT_ADMIN_TOKEN` and -`STOCK_BOT_SERVICE_TOKEN` values (at least 32 characters; generate each with -`openssl rand -hex 32`). An optional distinct `STOCK_BOT_READ_TOKEN` permits read-only -access. The same service token must be available to internal HTTP clients and servers. -Never put these tokens in `VITE_*` settings, URLs, source files, or logs. - -CLI clients use `Authorization: Bearer `. The dashboard sign-in exchanges an -admin/read token for a signed one-hour HttpOnly, SameSite=Strict cookie; it does not store -the token in localStorage or include it in the bundle. Production cookies require HTTPS. -Read-only access cannot mutate data; all mutation/admin operations require admin/service -access. Internal services do not accept browser cookies. WebSocket upgrades authenticate -and validate browser Origin. Session-key rotation invalidates issued cookies; logout clears -the browser cookie (copied cookies remain valid until expiry or key rotation). This is an -operator-access boundary, not a multi-user identity/tenant system. - -Dashboard/API URLs must be same-site for the strict cookie policy. In local development, -use matching hostnames (`localhost` for both, or `127.0.0.1` for both), not a mixture. - -`STOCK_BOT_HTTP_HOST` defaults to `127.0.0.1`. Set it explicitly for containers. Set -`STOCK_BOT_ALLOWED_ORIGINS` to an exact comma-separated list of trusted frontend origins; -production same-origin requests are supported, and reverse-proxy deployments must include -the public HTTPS origin. Wildcard/null origins are rejected. For isolated local demos only, -`STOCK_BOT_AUTH_DISABLED=true` is allowed on a loopback development/test listener, never -in production. Health endpoints remain public. TLS termination and external rate limiting -belong at the deployment boundary; do not expose development services directly. - -The root `.env` and `apps/stock/web-app/.env` are intentionally tracked for this private, -local-development repository. Other environment files remain ignored; -`bun run audit:secrets` rejects unexpected tracked environment files outside these two -explicit exceptions (WCAG excluded). It is not a complete secret scanner. Keep production -credentials out of these files. Committed values remain in Git history; rotate any real -credentials before sharing the repository or if access changes. Logging still redacts -sensitive fields, bearer tokens, credentialed URLs, and sensitive URL query parameters. -Development database/admin-UI Compose ports bind to loopback; existing containers must -be recreated for changed port bindings to take effect. - -## Pipeline safety - -Routine exchange/symbol/provider-mapping syncs are non-destructive. Legacy -`clearFirst: true` requests are rejected; scheduled exchange syncs no longer reset data. -When upgrading a long-lived Dragonfly/BullMQ instance from an earlier release, remove any -stale repeatable IB sync jobs left in the ingestion queue so old repeat schedules do not -keep firing after scheduled jobs default off. -The transactional sync paths share one checked-out PostgreSQL connection and one -transaction-scoped advisory lock. SQL errors roll back the whole batch and sync status, -and existing curated exchange/provider mappings are preserved. Do not add pooled -`query('BEGIN')` calls: use a transaction-scoped repository. - -Reference-data reset is a separate admin maintenance operation. Send a JSON body to -`POST /api/pipeline/clear/postgresql` with an explicit `type` (`provider_mappings`, -`exchanges`, or `all`) and `confirmation: "DELETE STOCK REFERENCE DATA:"`. -There is no default scope. A mapping-only reset deletes symbol-provider mappings only; -an exchange-only reset fails atomically if symbols still reference exchanges; `all` -deletes reference mappings, symbols, and exchanges in foreign-key order. These resets do -not delete backtest history, prices, or trading records. The dashboard requires typing -the matching confirmation. Generic queue access remains administrator-only. - -`bun run test:native` is part of `bun run check`. The stochastic tests explicitly cover -warm-up (14-bar K plus 3-value D needs 16 bars), invalid periods, golden values, and -incremental/batch parity; no synthetic D values are produced before warm-up completes. -`bun run test:postgres` additionally requires `PIPELINE_TEST_DATABASE_URL` pointing to a -**disposable database whose name starts with `stock_bot_safety`**. It creates/drops isolated -test schemas and verifies real rollback, foreign-key constraints, idempotency, and competing -transaction locking. Set `BACKTEST_TEST_REDIS_URL` to a dedicated Redis fixture using database -15 as well; queue names are unique per test. The durability tests cover HTTP acceptance, -outbox rollback, immutable requests, migration replay, hard-killed owners, stale-write fencing, -cancellation races, retry exhaustion, disconnected publishing, and lost-job redelivery with -the real native engine. CI provisions PostgreSQL and Redis and runs this additional gate. -It is separate from the infrastructure-free `check`; never point tests at production. diff --git a/REVIEW.md b/REVIEW.md deleted file mode 100644 index e6bdc90b..00000000 --- a/REVIEW.md +++ /dev/null @@ -1,402 +0,0 @@ -# Architectural & Quantitative Review of `docs/PLATFORM-PLAN.md` - -**Reviewed against:** `stock-bot` working tree at `HEAD = c353ddbe` (+ uncommitted env-safety/compose WIP), QA MongoDB `stock` (read-only via `MONGODB_READ_URI` as `studio_stock_bot_read@stock`), deployed QuestDB `10.2.0`, `docs/data-pipeline/phase1-investigation.md`, October backlog ADRs (`ADR-001`–`ADR-008`), and current QuestDB / IBKR API / marimo documentation. -**Date:** 2026-11-26 - -> **Verification tags used throughout this review** -> - **`[Verified: repo]`** — confirmed directly in source, SQL migrations, tests, or committed benchmark measurements (`file:line` cited). -> - **`[Verified: QA Mongo / PG]`** — confirmed via read-only queries against the 31 collections in `stock` (`studio_stock_bot_read`) and `trading_bot` PostgreSQL. -> - **`[Verified: external]`** — confirmed against deployed QuestDB `10.2.0` (`SELECT version(), build`), current QuestDB 9.x/10.x docs, IBKR TWS/Web API docs, and marimo 2025/2026 docs. -> - **`[Assumed]`** — explicitly stated engineering or market assumption not directly observable in the repo or ingested snapshot. - ---- - -## 1. Executive Summary - -### Is the plan sound? - -**Directionally yes; mechanically no — several load-bearing assumptions in Sections 5, 6, 7, 9, and 13 fail against the actual raw data in QA MongoDB and the existing code.** - -Your core strategic instincts are right: **signal-first before strategy-first**, **permanent `listing_id` keys**, **mandatory multiple-testing adjustment via a trial ledger**, **desktop MCP copilot first (D2)**, and **keeping the deterministic fixed-decimal Rust financial kernel (`apps/stock/engine/src/financial/*`) as the sole accounting authority**. The October backlog left you with an unusually strong foundation for invariant enforcement (write-once PostgreSQL triggers, 8-decimal `BigRational`-backed postings, and a real seccomp/cgroup Docker + Rust PID1 sandbox). - -However, the plan was written against an *idealized* mental model of what the vendors delivered and how QuestDB, the NAPI engine boundary, and the holdout gates behave. In reality: -- Your primary fundamentals (`qmFinancials`, `eodFinancialsOLD`, `eodFundamentalsOLD`) and macro (`teData`) collections **lack point-in-time filing/release dates and restatement/vintage history**; `eodIntraday1M` (`3.40B` bars) is **already split-adjusted** while `eodPrices` has **raw OHLC + split-adjusted volume**; and `eodSymbolChange` contains **only 230 US rows from 2024–2025**. -- Section 6's `ISIN + MIC` blocking fails on **>80–90% of `ibSymbols`** because IB tags NYSE, Nasdaq, and TSX stocks with secondary execution/ATS venues (`AEQLIT`, `ARCAEDGE`, `BEX`, `IEX`, `OTCLNKECN`) rather than primary listing MICs. -- Today's "sealed" holdout is **readable in plaintext JSON by any `sb-research.*` agent token**, the Rust/TS pull loop runs at **~5,400 bars/s** (making universe-scale callbacks unviable without a feature side-channel and atomic rebalancing fixes), and a solo-developer Phase A→C waterfall delays your first honest signal test by months. - -### The three things most likely to sink it - -1. **Silent phantom alpha from vendor data illusions (Sections 5, 6, 7).** Treating `eodFinancialsOLD.filingDate` as real (`99.26%` equal `reportDate`), `teData` as release-dated (`0%` release dates, 100% final-revised values), `eodIntraday1M` as raw (it is retroactively split-adjusted, so applying `adj_factors` double-adjusts every split), `eodPrices.volume` as raw (it is split-adjusted, inflating historical dollar-volume capacity by $10\times\text{–}56\times$), and exchange-delisted bars (`SIVB.US` ending at `$106.04`) as terminal without OTC-pink continuation (`SIVBQ.US` → `$0.006`) or bankruptcy delisting returns will systematically manufacture fake 3.0+ Sharpe backtests that agents will aggressively mine. -2. **Unplugged trial-ledger bypasses and adaptive holdout burn (Sections 1, 9, 11, 12).** Today `sb-research.*` tokens are explicitly allowed to export full holdout OHLCV JSON (`research-agents.service.ts:51`), agent budgets enforce concurrent (`maxActiveTrials`) rather than cumulative lifetime limits, and giving Claude Code / marimo raw table access (`stockbot.data.bars()` or raw SQL) lets an agent evaluate 5,000 signals in Polars memory and log `N = 1` on the winner. Worse, letting unattended campaigns (§15) touch the holdout and feed pass/fail into the Knowledge Base / Studio `evolve` loop adaptively overfits the holdout within weeks. -3. **Solo-developer infrastructure sprawl before testing one real signal (Sections 5, 9, 14, 16).** Building a full 6-pass security master + review UI, curating 10 datasets into QuestDB, writing a dual-backend QuestDB↔Parquet parity harness, building 4 playground pillars, and extending the single-asset Rust engine into a multi-currency long/short portfolio engine *serially* before testing a single cross-sectional hypothesis is ~9–12 months of plumbing. - ---- - -### Verdicts on Decisions Log (D1–D9) - -Per ground rules, D1–D8 are treated as settled unless concrete evidence proves a failure mode: - -| # | Decision | Verdict | Concrete Evidence & Required Adjustment | -| --- | --- | --- | --- | -| **D1** | QuestDB for all curated data + parity harness | **Challenge partially** | Keep **QuestDB `10.2.0`** for intraday (`bars_1m`/`5m`/`1h`) where `SAMPLE BY` and WAL streaming excel, **but put daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features directly in Parquet + DuckDB from Day 1, and drop the parity harness.** QuestDB `ASOF JOIN` breaks on long-format EAV `fundamentals` and regresses fiscal periods on restatements/10-K comparative backfills; `DEDUP UPSERT KEYS` destroys `known_at` history or breaks `LATEST ON`; and `libs/data/questdb` is currently broken/disabled (`data-pipeline/src/index.ts:66`). *(See Finding F3.)* | -| **D2** | Desktop copilot first via MCP | **Settled (with boundary fix)** | Keep D2, **but** distinguish interactive desktop Claude Code (which has host shell/DB access in `studio.config.json:5,9`) from autonomous campaign agents (which must run in network-isolated containers with MCP-only access), and air-gap the final Vault Holdout from both. *(See Finding F4.)* | -| **D3–D8** | US+CA priority, incremental UI, Step 1 merge first, IB live end-state, full strategy & lab scope | **Settled** | Sound; sequenced into vertical slices in Section 4 so D7/D8 do not block early research. | -| **D9** | **marimo** for Python labs inside the app | **Confirm (with 4 rules)** | Confirm marimo over Jupyter (`[Verified: external]`). Pure `.py` git diffs, deterministic DAG execution, `marimo check --format=json` static validation for LLM edits, `marimo edit --mcp`, and zero-RAM `marimo export html` snapshots fit agentic quant research far better than `.ipynb`. Enforce: **(1)** separate origin (never same-origin `allow-same-origin` with `web-app`'s `SameSite=Strict` session cookie), **(2)** static HTML snapshots by default in the Agent Lab Feed (`--session-ttl 300` for on-demand `marimo run`), **(3)** marimo's `CLAUDE.md` rules + `marimo check` pre-hook to prevent `MB002` variable-redefinition errors and `_underscore` cell-local scoping so intermediates don't pin GBs of RAM, and **(4)** `register_signal` materializes batch feature columns rather than translating Python into TS. *(See Findings F5 & F11.)* | - ---- - -## 2. Findings Ranked by Impact - ---- - -### F1 [CRITICAL — PIT & Data Integrity] — Raw Fundamentals, Macro, Earnings, Filings, and Shorts Cannot Support the Plan's `known_at` Claims as Written - -- **What the plan says (§5 lines 248–251, §7 lines 364–371):** - - Fundamentals (`qmFinancials`, `eodFinancialsOLD`, `eodFundamentalsOLD`): *"Point-in-time by filing date (`known_at`), not period end; restatements as new versions."* - - Macro (`teData`): *"release date as `known_at`."* - - Filings (`qmFilings`): *"insider transactions extracted where present."* - - Earnings (`qmEarnings`), Shorts (`ceoShorts`), Corporate actions (`qmSplits`, `qmDividends`, `eodSymbolChange`), FX (*"to be sourced"*). - -- **What I found (`[Verified: QA Mongo]`):** - Every dataset in Section 7 was sampled and audited via `MONGODB_READ_URI`: - - | Dataset (Collection & Count) | Empirical Audit Result in QA MongoDB | Real PIT `known_at` Derivable? | Honest Fallback & Research Ruled Out | - | --- | --- | --- | --- | - | **Fundamentals — QM** (`qmFinancials` `1.86M` + omitted `qmFinancials-old` `908k`) | **0 / 5,000 (`0.0%`)** have `filingDate` or `acceptedDate`; only `reportDate`, `periodEndDate`, `created_at` (2025 crawl). Unique-indexed on `(qmSearchCode, reportPeriod, reportDate)` and overwritten in place → **0 restatement versions** across `AAPL`, `NVDA`, `SMCI`, `TSLA`, `SHOP:CA`, `RY:CA`, `X:CA`. | **Only `filingDate` via `qmFilings` join; NO restatement history.** | Join `(listing_id, periodEndDate)` to earliest matching `10-Q`/`10-K`/`40-F`/SEDAR `52-109` filing `timefiled` in `qmFilings`. Where unmatched, add statutory deadline lag (**US: +45d Q / +90d FY; CA TSX: +45d Q / +90d FY; CA TSXV/CSE venture: +60d Q / +120d FY** per NI 51-102) + flag `known_at_quality = 'estimated_lag'`. **Rules out:** restatement alpha, pre-restatement surprise studies, exact filing-day fundamental triggers on unlinked rows. | - | **Fundamentals — EOD** (`eodFinancialsOLD` `2.98M`, `eodFundamentalsOLD` `106.6k`) | In `eodFinancialsOLD` (20k sample): **`19,851 / 20,000` (`99.26%`) have `filingDate === reportDate`** (30–90d look-ahead!). In `eodFundamentalsOLD`: `filing_date` is `null` across quarters, `Highlights`/`Valuation` are unversioned scrape-time snapshots, and **currency labels are corrupted on CDRs** (`AAPL` on `NEO`, `_id: 658615f03d1ee2d2611de872`, labels Apple's `$335.0B` USD `totalAssets` as `"CAD"` on alternating quarters!). | **No.** | **Quarantine `eodFundamentalsOLD` `Highlights`/`Valuation` completely from backtests** (live screener display only). Use `eodFinancialsOLD` only for pre-QM history with mandatory +45d/+90d/+120d lag, ignoring its bogus `filingDate == reportDate`, and cross-check statement currency against magnitude/instrument currency. | - | **Macro** (`teData` `14,794` docs) | Every document stores `data: [{ d: "YYYY-MM-01", v: }]` with `lastUpdated: 2026-04-02` (e.g., US `GDP CQOQ` `{d: "2025-12-01", v: 0.7}`, US `NFP TCH` `{d: "2026-02-01", v: -92}`, CA `CACPIYOY` `{d: "2026-02-01", v: 1.8}`). **Zero release dates; zero initial/revised vintages.** | **No.** | Apply conservative publication lags (`+1d` central-bank rates `FDTR`/`CCLR`; `+35d` monthly CPI/NFP/unemployment; `+65d` initial / `+90d` final quarterly GDP) and restrict `teData` to **coarse slow-moving regime filters**. **Rules out:** macro release event studies, macro surprise trading, and un-revised real-time GDP/NFP models (unless ALFRED/FRED + StatCan real-time vintages are ingested). | - | **Earnings** (`qmEarnings` `444,865` docs) | **`297,779 / 444,865` (`66.94%`)** have `announceTime: "N/A"` (`80,481` `AMC`, `66,605` `BTO`). `consensusEps` is overwritten in place (`created_at: 2025-06-29`), with no estimate revision history. | **Date yes; intraday session only on 33% (unless linked to `qmFilings`).** | Link to `qmFilings` (`8-K` / Canadian `News release` `timefiled`) to resolve BMO vs AMC. Where `announceTime == "N/A"` and unlinked, stamp `known_at = reportDate 16:05 ET` (tradable at `T+1` open). **Rules out:** pre-announcement analyst-revision drift and `T+0` open PEAD entries on un-timestamped rows. | - | **Filings** (`qmFilings` `30.52M` docs) | `100%` of sampled rows carry second-precision `timefiled` (`"2024-10-08T17:30:13 EST"`, `"2023-11-28T10:02:05 EST"`). **However, documents contain metadata + external QuoteMedia URLs (`htmllink`/`xlslink`) ONLY — zero filing body text and zero parsed Form 4 / SEDI share counts or buy/sell indicators** (verified on AAPL Form 4 `acc: 0000320193-24-000114`, `filer: "MAESTRI LUCA"`). | **Yes (`timefiled`, convert `EST`/`EDT` cleanly to UTC).** | Filing-arrival/form-type event studies work immediately (`Form 4` count, `144` sale notice count, `8-K`, `NI 43-101`, `52-109`). **Rules out:** insider net-buy dollar/share-size signals until Form 4 XML / SEDI is fetched and parsed. | - | **Dividends & Splits** (`qmDividends` `495,942`, `qmSplits` `18,751`) | `qmDividends`: `408,295` (`82.33%`) have valid `declared < date` (ex-date); `86,588` (`17.46%`) lack `declared`; `1,059` have `declared >= date`; CAD dividends carry bogus `usdFxRate: 1` (`X:CA` `_id: 6861bc9c9aba109fccfe8659`). `qmSplits`: **only `5,646 / 18,751` (`30.11%`)** have `declared`, plus `258` no-op `splitratio == 1` rows. | **Ex-date accounting: 100%. Announcement `known_at`: 82% divs, 30% splits.** | Filter `splitratio == 1` and ignore `qmDividends.usdFxRate` (join real `fx` instead). Accounting/adjustments trigger on `ex_date` (known to market at `ex_date` open). **Rules out:** split-announcement drift on the 70% missing `declared` unless linked to `qmFilings`. | - | **Symbol Changes** (`eodSymbolChange` `230` docs) | **230 rows total**, **100% `exchange: "US"`**, `effective` spanning **`2024-08-12` to `2025-07-03` only** (`0` Canadian rows, `0` pre-Aug-2024 history). | **Useless for 20y history.** | Cannot drive `listing_symbol_history` (see Finding F2). | - | **CEO Posts & Shorts** (`ceoPosts` `14.78M`, `ceoShorts` `692,904`) | **100% Canadian** (`CNQ` 4,583, `TSX` 4,127, `CDX` 3,292, `AQL` 587; `0` US). `ceoPosts` has ms `timestamp`, **but `360 / 20,000` (`1.80%`) have `edited != null`** where `spiel` text was overwritten later, and includes `@thenewswire` press-release bots (`bot: "1"`). `ceoShorts` timestamps (`SHOP.TO`: `2025-05-15`, `2025-05-31`, `2025-06-15`) are **CIRO/IIROC semi-monthly report period-ends, NOT publication dates** (published 3–4 business days later). | **Posts: yes (with edit guard). Shorts: requires +4 business-day lag.** | For `ceoPosts`, if `edited != null`, either set text `known_at = edited` or exclude edited text from NLP while keeping unedited post-count pulse at `timestamp`; separate `bot == "1"` newswires from retail posts! For `ceoShorts`, set `known_at = timestamp + 4 Canadian business days (17:00 ET)`. **Rules out:** US social/short research from CEO.ca. | - | **FX (`USD/CAD`)** | **Already ingested (`[Verified: QA Mongo]`)!** `eodPrices` has `CAD.FOREX` (`12,109` daily bars, `1971-01-04..2025-08-13`) and `CADUSD.FOREX` (`9,351` daily bars); `eodIntraday1M` has **`5,202,056` 1m bars** for `CAD.FOREX` + `5,204,726` for `CADUSD.FOREX`; `teMarketData` has `USDCAD` (`2,865` daily bars through `2026-04-02`). | **Yes.** | No external FX sourcing needed for Phase A–E; curate `CAD.FOREX` (1m + 1d) supplemented by `teMarketData.USDCAD` (post-Aug 2025). | - | **Futures** (`ttFutures` `1.46M` docs) | Individual historical contracts (`AD90M`, `CD`, `CL`, `SP`, `US`) from 1959 onward with **corrupted date strings** (`minDate: "2001-/0-2/"`, `maxDate: "NaN-at-e\""`). | **Dirty / archival.** | Defer completely out of scope until post-equity live. | - -- **Recommendation:** Add an explicit `known_at_source` enum (`'filing_timestamp' | 'exchange_bar_close' | 'declared_date' | 'statutory_lag_estimate'`) to every curated PIT row, implement the `qmFilings` → `qmFinancials`/`qmEarnings` timestamp join + NI 51-102 / SEC statutory lag fallbacks + `+4bd` CIRO short lag, quarantine `eodFundamentalsOLD` snapshots, and restrict `teData` to lagged regime features (adding FRED/ALFRED + StatCan real-time vintages later only if macro-release alpha becomes a priority). - ---- - -### F2 [CRITICAL — Price/Volume/Survivorship Corruption] — Split-Adjustment Asymmetry Across `eodPrices`, `qmPrices`, and `eodIntraday1M`, Plus Unmodeled Terminal Delisting Losses - -- **What the plan says (§5 lines 245–247, §6 lines 317–320, §9 lines 430–431):** - - `bars_1m`, `bars_5m`, `bars_1h`, `bars_1d` store **raw OHLCV**, with `adj_factors` applied on read or materialized (`ADR-003:17` also mandates raw prices for share/cash execution). - - Universe is *"survivorship-free"* with *"delistings with delisting returns"*. - -- **What I found (`[Verified: QA Mongo]`):** - 1. **`eodIntraday1M` (`3.40B` bars) is ALREADY retroactively split-adjusted, whereas `eodPrices` (`845.7M` bars) has RAW OHLC:** - - Tested on `NEXM.V` / `NEXM:CA` (`1:20` reverse split on `2025-06-20` in `qmSplits`, `splitratio: 20`): pre-split `eodIntraday1M` on `2025-06-18 16:01` already reports `close: 24.29` (matching post-split `2025-06-20 18:02` `close: 24.2799`), instead of raw `~$1.21`! Storing `eodIntraday1M` into `bars_1m` as "raw" and applying `adj_factors` **double-adjusts every split across 3.4 billion bars**. Conversely, `qmIntraday` (`173M` bars) stores *both* raw (`open..close`, `sharevolume`) and split-adjusted (`adjustedopen..adjustedclose`, `avolume`). - 2. **`eodPrices.volume` is SPLIT-ADJUSTED while `eodPrices.close` is RAW (10×–56× dollar-volume inflation!):** - - Tested on `X.TO` / `X:CA` (`5:1` split on `2023-06-14`): on `2023-06-13`, `eodPrices` has `close: 147.78` (raw), `adjustedClose: 28.1493`, and **`volume: 676,795` (`= 5 × 135,359`)**, whereas `qmPrices` has `unadjustedclose: 147.78` and **`sharevolume: 135,359` (raw)**! - - Tested on `NVDA` (`10:1` split on `2024-06-10`): on `2024-06-07`, `eodPrices` has `close: 1208.88` (raw) and **`volume: 412,385,776` (`= 10 × 41,238,580`)**, whereas `qmPrices` has `unadjustedclose: 1208.88` and **`sharevolume: 41,238,580` (raw)**! - - Multiplying `eodPrices.close * eodPrices.volume` yields **$498.5B/day** for NVDA pre-split (10× overstated) and **56× overstated pre-2014 liquidity** for AAPL — completely breaking universe dollar-volume filters and `ADR-003:12`'s `participation_rate * bar.volume` fill-capacity cap! - 3. **Delisted symbols exist (`52,745` US + `3,136` CA in `eodSymbols`; `15,790` US + `3,626` CA inactive in `qmSymbols`), BUT terminal delisting losses & spliced bankruptcies corrupt naive survivorship:** - - **Primary → OTC Pink venue drop hides bankruptcy wipeouts:** `SIVB.US` (`Exchange: NASDAQ`, `ISIN: US78486Q1013`) ends on `2023-03-09` at **`close: $106.04`**, then reappears as a *separate* symbol `SIVBQ.US` (`Exchange: PINK`, same ISIN `US78486Q1013`) trading pennies down to `$0.006`. Under §6's `listing = instrument + mic`, `XNAS` (`SIVB`) and `OTCM` (`SIVBQ`) are distinct `listing_id`s: marking or exiting `SIVB` at its last `XNAS` bar (`$106.04`) misses a **-99.5% loss**! - - **Missing terminal cancellation bars:** `BBBYQ.US` ends on `2023-09-29` at `$0.0789` with no `$0.00` (-100%) Chapter 11 cancellation event; meanwhile cash M&A (`AAR-UN.TO` ending `2018-05-25` at `$8.09`, `X.US` ending `2025-06-20` at `$54.84`) ends near deal price. - - **Overwritten pre-bankruptcy tickers in EOD:** `GM.US` in `eodPrices` starts `2010-11-18` (post-bankruptcy IPO) and `HTZ.US` starts `2021-07-01` — pre-2009 Old GM and pre-2020 Old Hertz were overwritten under their root tickers. - -- **Recommendation:** - 1. **Un-adjust `eodPrices.volume` and `eodIntraday1M` OHLCV** during Step 2 curation using cumulative post-bar split factors from `qmSplits` (cross-checked against `eodPrices` step changes and `qmPrices`/`qmIntraday` raw series where overlapping), so `bars_*` is genuinely raw in both price *and* share count; reject or flag any symbol where split un-adjustment leaves an unexplained step jump. - 2. **Link exchange delistings to same-ISIN OTC continuation (`XNAS`/`XNYS` → `OTCM`)** as a mandatory corporate-action liquidation bridge: if a strategy's universe excludes OTC, force-exit at the **first tradable OTC open** (capturing the `$106.04 → $0.50` SVB gap loss!), and if a delisted equity has no M&A/cash payout filing and disappears below `$1.00` (or with `-Q` bankruptcy suffix), apply a Shumway terminal delisting return (**`-30%` default on involuntary exchange delisting without OTC print; `-100%` on cancelled `PINK`/`Q` shares**). - ---- - -### F3 [CRITICAL — Storage Architecture (D1 & §5)] — QuestDB `ASOF JOIN`, `DEDUP`, and `INT` Keys Break on Bitemporal Fundamentals and Cross-Sectional Scans; `libs/data/questdb` Is Broken Today - -- **What the plan says (§3 D1, §5 lines 192–253):** - - Keep all curated data (`bars_*`, `adj_factors`, `corporate_actions`, long-format `fundamentals (listing_id, period_end, field)`, `events`, `shorts`, `macro`, `fx`) in QuestDB with integer `listing_id` keys and `known_at` on every row (`known_at <= asOf` as a query rule), plus a dual-backend parity harness from Day 1. - -- **What I found (`[Verified: external — QuestDB 10.2.0]` + `[Verified: repo]`):** - 1. **Deployed QuestDB version discrepancy:** `docker-compose.yml:67` and `docker-compose.dev.yml:82` use unpinned `questdb/questdb:latest` (`quant` pulled **QuestDB `10.2.0`**, while the pre-migration local image was built `2025-05-30`). Worse, `apps/stock/data-pipeline/src/index.ts:66` sets `enableQuestDB: false` (*"Disabled for now due to auth issues"*), and `libs/data/questdb` is broken: `client.ts:272` & `query-builder.ts:230` emit deprecated `LATEST BY`, `client.ts:323` runs invalid `SELECT * FROM table_columns WHERE table_name = ?`, `schema.ts:313-335` silently drops `WAL`/`dedup`/`capacity`/`index` options, `query-builder.ts:95-111` interpolates raw SQL strings, and `schema.ts:28-156` auto-creates 6 legacy ticker-keyed tables on every `connect()`. - 2. **Long-format EAV `fundamentals (listing_id, period_end, field, value, known_at)` breaks QuestDB `ASOF JOIN`:** - - QuestDB `ASOF JOIN` requires both tables to be ordered by their **designated timestamp** and returns **at most ONE right-hand row** per left row (`bars_1d ASOF JOIN fundamentals ON (listing_id)` returns **1 random `field`**, dropping the other 120 fields!). Joining 20 fields requires 20 chained self-joins, and `PIVOT` strips the designated timestamp while clobbering un-updated fields to `NULL` on partial filings. - 3. **The Bitemporal Restatement / Comparative-Backfill Trap:** - - Suppose Q1 (`period_end = 2024-03-31`) is filed `2024-05-10`, Q2 (`period_end = 2024-06-30`) is filed `2024-08-10`, and on `2024-09-01` a 10-Q/A restatement (or 10-K comparative table) updates Q1 (`period_end = 2024-03-31`, `known_at = 2024-09-01`). At bar `2024-09-15`, a 1D `ASOF JOIN` on `known_at` picks `2024-09-01` and **overwrites Q2 with restated Q1**, moving the company backward in fiscal time! Nor can `ASOF JOIN` compute 4-quarter TTM sums (`E/P`, `FCF yield`, `ROE`). - 4. **`DEDUP UPSERT KEYS` vs. `known_at` Versioning on `bars_*`:** - - QuestDB WAL `DEDUP UPSERT KEYS(ts, listing_id)` is **destructive last-writer-wins**: updating a historical bar with a new `known_at` destroys prior history and makes `WHERE known_at <= old_asOf` **drop that bar entirely** (creating a missing-date hole!). Putting `known_at` in the dedup key (`DEDUP UPSERT KEYS(ts, listing_id, known_at)`) creates duplicate `(listing_id, ts)` rows that QuestDB's `LATEST ON` **cannot** deduplicate across a time range because `LATEST ON` only accepts the designated timestamp (`ts`) and returns 1 row per partition key (`75M` `(listing_id, ts)` keys!). - 5. **`INT` `listing_id` Disables QuestDB's Fast Paths:** - - In QuestDB, `LATEST ON ts PARTITION BY col` only halts backward partition scans early when `col` is `SYMBOL` (dictionary-encoded); on `INT` it scans every partition in range. `ASOF JOIN` likewise uses specialized memoized paths on `SYMBOL`. At 50k–400k listings across 10 tables, `SYMBOL` must be declared `SYMBOL CAPACITY 65536 NOCACHE` to avoid JVM heap bloat. - 6. **QuestDB Native Parquet Reality (`QuestDB 10.2.0`):** - - QuestDB 10.2 supports `read_parquet()` and `ALTER TABLE ... CONVERT PARTITION TO PARQUET`, which cuts disk usage 5–10× on cold `bars_1m` partitions — **but queries slower inside QuestDB than native mmap** and rewrites entire partitions on out-of-order writes, and its internal `table~N/` directories (`_txn`/`_meta`) are not external Hive Parquet lakes. - -- **Recommendation:** **Amend D1 now to split curated storage by workload behind `MarketDataStore`, and cut the dual-backend parity harness.** - - **DuckDB + Hive Parquet (`/mnt/data/stockbot/curated/*.parquet`):** Store `bars_1d`, `corporate_actions`, `adj_factors`, bitemporal `fundamentals`, `events`, `shorts`, `macro`, `fx`, and `features` in ZSTD Parquet queried via DuckDB. DuckDB handles 75M daily rows (`20y × 15k` listings) with `RANK() OVER (PARTITION BY ts)`, true 2D bitemporal `QUALIFY row_number() OVER (PARTITION BY listing_id, period_end ORDER BY known_at DESC) = 1`, and zero-copy Arrow export to Polars/marimo in **<1–3 seconds** on `quant`'s SN850X NVMe + 125 GiB RAM. - - **QuestDB `10.2.0` (pinned image tag, rebuilt thin client):** Reserve strictly for `bars_1m` (deriving `5m`/`1h` via `SAMPLE BY` or materializing where needed) + live/paper hot streaming bars, using `listing_id SYMBOL CAPACITY 65536 NOCACHE`, single-version `DEDUP UPSERT KEYS(ts, listing_id)` + a separate sparse `bar_revisions` table, and converting sealed `>90d` `bars_1m` partitions to Parquet (`CONVERT PARTITION TO PARQUET`) only if NVMe space requires it. - - *(Close runner-up if you insist on keeping 100% of v1 in QuestDB: materialize wide forward-filled `fundamental_pit_snapshots` + TTM columns in `data-pipeline` before writing to QuestDB, store `listing_id` as `SYMBOL NOCACHE`, keep `bars_1d` single-version + sparse `bar_revisions`, and still skip building the DuckDB parity harness until QuestDB fails a measured exit target.)* - ---- - -### F4 [CRITICAL — Statistical Rigor & Security (§1, §9, §11, §12)] — Active Holdout Leak in `web-api` Today, Six Trial-Ledger Bypass Vectors, and Adaptive Holdout Overfitting - -- **What the plan says (§1 lines 44–50, §9 lines 437–458, §11 lines 531–535, §15 line 671):** - - Sealed out-of-sample holdout *"Exists"*; every signal analysis, screen, and backtest from any agent, notebook, or UI is recorded in the trial ledger; notebooks get a *"flagged raw-SQL escape hatch"*; and *"Everything up to Validated can run unattended."* - -- **What I found (`[Verified: repo]`):** - 1. **The "sealed" holdout is wide open across calls today:** - - While a single `ChronologicalValidation` state machine (`apps/stock/web-api/src/services/chronological-validation.service.ts:163-444`, `database/postgres/init/24-chronological-validation.sql`) freezes `train` selection before running `test`, **`research-agents.service.ts:51` explicitly permits `sb-research.*` tokens to call `GET /api/v2/datasets/canonical/:hash/export`!** Because `submitValidation` immediately inserts the `test` slice into `backtest_datasets` and returns its hash (and the parent `backtestId` spans `train+validation+test`), **any agent can download every bar of the `test` holdout in plaintext JSON** (`scripts/research-client.ts:782-797`), run whole-window sweeps on `backtestId`, read all other principals' `test` trade logs via unscoped global `GET`s (`research-agents.service.ts:46-53`), and re-submit `v1, v2, ..., v500` against `test` with **zero cumulative budget** (`28-research-agents.sql:100-191` only caps concurrent `active_trials` and per-experiment `<= 100` runs, never lifetime trials!). - 2. **No trial ledger, DSR, PBO, or CPCV exists in the live stack:** - - `chronological-validation.ts:30-31` hardcodes `labelHorizonMs: z.literal(0)` (no purge/embargo). The only DSR code in the repo (`apps/stock/analytics/src/analysis/statistical_validation.py:56-58, 130-156`) is dead (`503` disabled in `CL35`), omits skewness/kurtosis and cross-trial Sharpe variance, and calls `calculate_deflated_sharpe_ratio` with default `num_trials = 1` (`ln(1) = 0`)! - 3. **Three fatal bypasses in the proposed MCP + Python SDK + marimo design:** - - **In-memory Polars evasion:** Once `stockbot.data.bars()` or MCP `query_data` returns a DataFrame to marimo or a script, an agent can loop over 5,000 expressions in Python memory with **zero SDK analysis calls** and register only the winner (`N = 1` logged instead of `5,000`). - - **Desktop Claude Code host access:** `studio.config.json:5,9` gives desktop agents `"shell": true` on the host where `.env` and unauthenticated QuestDB (`:9000`/`:8812`) live. - - **Raw-SQL escape hatch (§5 line 211):** Bypasses `known_at <= asOf`, holdout date fences, and trial counting simultaneously. "Flagging" a notebook does not stop an agent or human from copying the winning formula into a clean MCP backtest call. - 4. **Adaptive holdout destruction (§15 line 671):** Allowing unattended agent campaigns to run through `Validated` on the holdout and write verdicts to the Knowledge Base / Studio `evolve` loop turns the holdout into an adaptive training oracle ($k$ adaptive queries leak information at $O(\sqrt{k/T})$). - -- **Recommendation:** - 1. **Two-Tier Air-Gapped Holdout:** Split OOS into **(a) Research Validation (`ts < VAULT_CUTOFF_DATE`, e.g., trailing 24 months reserved)** evaluated via **Purged Walk-Forward + CPCV (`purge = horizon + warmup`, `embargo = max(5d, 0.01*T)`) + DSR/PBO** for unattended `Validated` gating, and **(b) a Physically Air-Gapped Vault Holdout (`ts >= VAULT_CUTOFF_DATE`)** stored in a separate vault path unreadable by `MarketDataStore`, `export`, marimo, or `sb-research.*` tokens. Only a human `Validated → Paper` action triggers a **one-shot Vault evaluation** (hard-capped at $\le 10$ vault burns/year in an immutable Postgres table, rolling forward annually). - 2. **Patch `research-agents.service.ts` & `28-research-agents.sql` immediately:** Remove `/export` from `sb-research.*`, scope `GET` routes by `allowedProjectIds`/grants, and add **cumulative per-campaign and daily trial + bar-evaluation counters** enforced in SQL triggers. - 3. **Define "related trial" deterministically & store return vectors for $\hat{N}$:** Group trials by **objective `(universe_market, horizon_bucket)`** (`{US, CA, US_CA} × {intraday, swing_1_10d, position_10d_plus}`), never by agent-invented `family` labels. Persist the **daily out-of-warmup return/IC vector** (float32 array, ~20 KB for 20y daily) of every evaluated variant in `trial_ledger` so **DSR** computes Bailey & López de Prado's **effective independent trials $\hat{N} = 1 + (N-1)(1 - \bar{\rho})$**, cross-trial Sharpe variance $\text{Var}[\{\widehat{SR}_n\}]$, and non-normal $(\hat{\gamma}_3, \hat{\gamma}_4)$, while **PBO (CSCV, $S=16$ slices)** runs over synchronous campaign return matrices $M_{T \times N}$. - 4. **Close notebook/agent bypasses:** Run autonomous agents in `--network` isolated containers talking **only** to the MCP/HTTP API (no raw SQL, no DB ports, no host shell); restrict the raw-SQL escape hatch to human localhost sessions over pre-vault views; and log data-pull footprints (`universe × window × features`) alongside every trial. - ---- - -### F5 [HIGH — Security Master (§6)] — Blocking on `MIC` Breaks on >80% of `ibSymbols`, Ticker Reuse (`FB`, `GM`, `HTZ`) Collides Without Validity Windows, and Naïve MongoDB Price Cross-Checks Are 13.6× Slower Due to Index Order - -- **What the plan says (§6 lines 260–351):** - - Pass 1 maps each provider exchange code to a canonical ISO 10383 `mic`. - - Pass 3 blocks candidates within **`country + MIC`**: Tier 1 = `Valid ISIN + MIC` (`IB, EOD`), Tier 2 = `CUSIP-derived ISIN + MIC` (`IB → EOD`), Tier 3 = `Normalized ticker + MIC (+ currency)`. - - Pass 4 compares overlapping daily closes per candidate pair; Pass 6 sources ticker history from `eodSymbolChange`. - -- **What I found (`[Verified: QA Mongo]` + `[Verified: repo]`):** - 1. **`ibSymbols` (`18,402` rows) stores execution/ATS venues, NOT primary listing MICs (`isPrimeExchId` is `null`):** - - Actual `ibSymbols` venue distribution (`[Verified: QA Mongo]`): - - **Canada (`3,846` rows):** `AEQLIT` (Cboe/NEO Lit ATS) = **`2,506` (`65.2%`)**, `VENTURE` = `826`, `TSE` = **`514` (`13.4%`)**. Over **83% of TSX-listed stocks** in `ibSymbols` (e.g. `CIA` = Champion Iron) have `exchangeId = "AEQLIT"` (`NEOE`), whereas EOD (`TO`) and QM (`TSX`) place them on `XTSE`! - - **US (`14,556` rows):** `OTCLNKECN` = `6,627`, `ARCAEDGE` = `1,067`, `AMEX` = `838`, `BEX` = `777`, `DRCTEDGE` = `682`, `EDGEA` = `523`, `IEX` = `509` (e.g., Agilent `A`!), `LTSE` = `426`, `MEMX` = `397`, **`NYSE` = ONLY `370` (`2.5%`)**, `CHX` = `310`, `NYSENAT` = `250`, **`NASDAQ` = ONLY `241` (`1.7%`)**! - - Meanwhile, `eodSymbols` puts `103,792` US rows under composite `eodExchange = "US"` (including **`44,970` `NMFQS` mutual funds** that must be excluded from equity universes, plus `262` `Exchange: null` and `288` `Exchange: "US"` rows), and existing `normalizeProviderSymbol` (`apps/stock/data-pipeline/src/normalization/provider-symbol.ts:34-49`) ignores `exchangeId` and `description`, skipping **100% of `ibSymbols`** today! - - **Result:** Blocking or matching Tier 1/Tier 2 on `ISIN + MIC` **misses >90% of US NYSE/Nasdaq stocks and >83% of TSX stocks in `ibSymbols`**! - 2. **Matching without temporal validity windows corrupts reused tickers (`FB` vs `META`, CSE duplicates):** - - Verified live collision (`[Verified: QA Mongo]`): EOD retroactively renamed Facebook's 2012–2022 bars to `META.US`, while `FB.US` is now **active** (`Name: "ProShares Trust ProShares S&P 500 Dynamic Buffer ETF"`, `Exchange: "BATS"`, `Isin: null`, bars starting `2025-06-26`). Meanwhile `qmFilings` (`30.5M` docs) keys historical 2012–2022 Facebook filings by `symbol: "FB"`! Static Tier 3 ticker matching attaches Meta's historical filings/events onto a 2025 S&P 500 Buffer ETF. Similarly, `qmSymbols` has duplicate `(symbol, exchange)` rows on `CNQ` (`VOY:CNX` active + `VOY:CC` inactive, `PKK`, `RIPP`, etc.). - 3. **ISINs and CUSIPs are NOT immutable across reorganizations and TSXV share consolidations:** - - `instrument(instrument_id, ISIN, CUSIP, ...)` assumes 1 permanent ISIN per company. In Canada (`XTSX`/`XCNQ`), every reverse split / name change / continuance issues a **new CUSIP and ISIN**, and corporate redomiciliations (`LIN` Praxair/Linde US → Ireland → UK ISINs; SPAC de-SPACs) change ISIN while the economic listing continues. - 4. **Pass 4 Price Cross-Check MongoDB Index Trap:** - - `eodPrices` (`845.7M` docs) has `{date: 1, eodSearchCode: 1}` and `{eodSearchCode: 1}` — **no `{eodSearchCode: 1, date: 1}` index**! Benchmarking 10 symbols via `MONGODB_READ_URI` took `309.6 ms` on `eodPrices` (scanning full 25y symbol history) vs `22.8 ms` on `qmPrices` (`13.6×` slower warm; seconds per symbol cold on uncached delisted symbols → many hours for 50k pairs). - -- **Recommendation:** - 1. **Two-stage resolution (Instrument first, Venue second):** Resolve **`instrument`** globally by Luhn-valid ISIN / CUSIP-derived ISIN (with an `instrument_identifier_history(instrument_id, id_type, id_value, valid_from, valid_to)` table for reorganizations/reverse-splits). Determine primary `listing (instrument_id, mic)` from **EOD `Exchange` + QM `exchange`** (filtering out `NMFQS` mutual funds from equity universes), and attach `ibSymbols` (`conid`) at **`(instrument_id, currency)`** — never treating IB `AEQLIT`/`IEX`/`BEX`/`ARCAEDGE` as primary listing MICs! - 2. **Precompute `[first_bar_date, last_bar_date]` per `(source, source_id)` before Pass 3:** Require overlapping active date windows on Tier 3/4 ticker matches, populate `provider_mapping.(valid_from, valid_to)` from observed bar/filing spans + corporate actions rather than relying on the 230-row `eodSymbolChange` table, and route non-overlapping same-ticker pairs (like pre-2022 `FB` vs 2025 `FB`) to separate `listing_id`s. - 3. **Execute Pass 4 Price Cross-Check via 25 stratified cross-sectional dates (`{ date: { $in: sampleDates } }`), NOT per-pair queries:** Querying `eodPrices` by `date` first hits `{date: 1, eodSearchCode: 1}` sequentially (or run Pass 4 in DuckDB *after* bulk-extracting US+CA daily closes), completing all US+CA candidate return-correlation & USD/CAD ratio checks in **<30 seconds** instead of hours. - ---- - -### F6 [HIGH — "One Engine" vs. Actual Design (§4, §8, §9, §11)] — Three Engines, 5× Conflicting Math Implementations, a 5,400 bars/s NAPI Bottleneck, Two Multi-Asset Rust Bugs, and a Five-Wall Python→TS Promotion Blockade - -- **What the plan says (§1 line 46, §8, §9, §11 lines 534–536):** - - *"One engine. The same Rust core runs backtest, paper and live."* - - Tier 1 fast vectorized screener *"Reopens deferred task P06"*. - - Tier 2 extends the Rust engine to multi-asset cross-sectional long/short portfolios; strategies stay sandboxed TypeScript; `register_signal(...)` promotes a Python notebook signal into the feature library and strategy lifecycle. - -- **What I found (`[Verified: repo]`):** - 1. **Three coexisting simulators + 5–6 conflicting indicator/metric implementations exist today:** - - Engines: **(a)** Canonical fixed-decimal Rust `financial/*`, **(b)** Legacy `f64` Rust `BacktestEngine` (`engine/src/backtest/engine.rs`), and **(c)** Legacy TypeScript `SimulationExecution` (`orchestrator/src/execution/SimulationExecution.ts`). - - Math divergence (`[Verified: repo]`): **RSI** has 3 incompatible formulas (on flat prices `gain=loss=0`, Rust `rsi.rs:72-77` returns **`99.01`**, Rust `calculate_rsi` returns **`100.0`**, TS `RsiIndicator` `rsi.ts:36-38` returns **`50.0`**, and `trailingSimpleRsi` uses simple rolling averages instead of Wilder smoothing!). **Sharpe, Sortino, Volatility, Annualization, and Max Drawdown** have 5–6 implementations using conflicting `ddof=0` vs `ddof=1`, `252` vs `365` vs `365.25` days/year, geometric vs arithmetic returns, and Sortino denominators (`return-statistics.ts:50-102` vs `simple_results.rs:174-235, 399-431` vs `performance.py:139-163` vs `statistical_validation.py:94-108`). - 2. **`P06` is mischaracterized (§9 line 418 vs `docs/development/backlog/tasks/P06.md`):** - - `P06` is a tiny declarative AST inside the event-driven Rust `Replay` loop requiring **exact economic-hash equivalence** — *not* a vectorized cross-sectional screener. A vectorized matrix screener (`Polars`/`DuckDB` computing `(T × N)` weights × forward returns minus linear turnover cost) intentionally omits integer lot rounding, cash reservations, and path-dependent halts: it **will** implement simplified portfolio math separate from Rust, and the plan should own that explicitly rather than calling it `P06`. - 3. **Two concrete multi-asset bugs inside `apps/stock/engine/src/financial/` today:** - - **Bug A — Non-atomic `Target` cash reservation blocks portfolio rotation (`matching.rs:1083-1136`, `risk.rs:564-566`):** `Ledger`, `RiskAccount`, and `MatchingAccount` already use multi-instrument `BTreeMap`s internally (single-asset is gated in TS at `native-worker.ts:49-51` and `candidate-execution.ts:27-42`), **but** `StrategyIntent::Target` submits `Sell A` and `Buy B` sequentially against `available_cash()`. Because pending `Sell A` proceeds are not credited until next-open fill, any fully invested cross-sectional rebalance rejects `Buy B` with `RiskRejection::InsufficientCash`! - - **Bug B — Sequential same-timestamp marking latches false drawdown halts (`ROADMAP.md:44`, `replay.rs:24-28`):** Updating marks lexically one instrument at a time at timestamp `t` trips irreversible portfolio daily-loss/drawdown halts on intermediate unhedged marks even when simultaneous offsetting long/short moves leave net equity flat. - 4. **The 5,400 bars/s NAPI + JSON wall (`conditional-review.md:27-28`, `api/canonical.rs:33-43`):** - - Every trading bar crosses JS↔Rust NAPI twice (`advance` + `submit`), double-parsing JSON inside `api/canonical.rs:33-43` and recursively cloning/freezing plain JSON state (`strategy-decision.ts:35-88`) — plus two Docker stdio pipe crossings per bar for sandboxed candidates (`candidate-sandbox.ts:279-323`). At ~5,400–7,400 bars/s, a single 20-year daily cross-sectional backtest over 8,000 listings (`40M` bars) takes **~1.8 hours** unless strategies trigger **only on rebalance barriers** (e.g., daily close / weekly) with batch binary/Arrow observation loading rather than stringified JSON per bar! - 5. **Five hard walls block moving a signal from Python/marimo to a TypeScript strategy today:** - - **(i)** `candidate-host.ts:29-42` bans **all `import`s** (even `@stock-bot/calculations`); **(ii)** `StrategyContext` (`libs/research/src/strategy-api.ts:39-60`) only carries OHLCV `PreparedBar`s — **zero channel for features, fundamentals, or events**; **(iii)** `Replay::validate` (`replay.rs:404-413`) requires `open/high/low/close > 0` (`Positive`), so signed signals/z-scores cannot even be passed as synthetic bars; **(iv)** `copyJsonState` bans `Float64Array`/`Map`; and **(v)** promoting a candidate to `paper-host.ts:34-37` drops the Docker/seccomp sandbox completely! - -- **Recommendation:** - 1. **Make Feature Materialization the sole Python → TypeScript bridge:** Define features once as versioned **DuckDB SQL or Python/Polars batch jobs** (`features//v.py|.sql`) that write `(listing_id, ts, known_at, value: f64)` to the `features` store. Add a read-only `features: Record` map to Rust `Replay` decision barriers and `StrategyContext`. Then Python notebooks, the vectorized screener, AND TypeScript strategies all read the **exact same precomputed feature values** — zero Python→TS indicator rewrites, and sandboxed TS strategies shrink to ~40 lines of pure sizing/rebalance logic! - 2. **Consolidate metrics & retire legacy engines:** Delete dead `apps/stock/analytics` metric code and retire legacy `f64` `BacktestEngine` + TS `SimulationExecution` once multi-asset cutover lands; make `libs/calculations` (`returnStatistics`, `drawdownAnalysis`, plus new DSR/PBO) the **single** metric calculator served by the Research Kernel API to UI, MCP, and Python SDK. - 3. **Fix Rust multi-asset replay before Phase C:** **(a)** Apply all bar marks at timestamp `t` atomically before evaluating `RiskAccount` drawdown/daily-loss latches; **(b)** add net-proceeds target rebalancing (`expected_sell_proceeds * (1 - haircut)` offsetting same-barrier buy reservations for next-open `Target` batches); **(c)** strip the duplicate `serde_json::Value` round-trip in `api/canonical.rs:33-43` and load datasets into Rust from Parquet/Arrow paths instead of `JSON.stringify` (which also hits PostgreSQL's 1 GB `JSONB` limit on universe datasets!). - ---- - -### F7 [HIGH — Phase 0 Safety & Bootstrap] — Three Undocumented Bugs in the Current Working Tree Break Phase 0 Isolation and Leak Secrets - -- **What the plan says (§2 lines 71–92, §6 line 351, §16 Phase 0, §17 lines 691–698):** - - Only 2 gates fail (`test:tooling` and `lint:check`); `audit:secrets` passes; `mongoReadOnly` rejects all MongoDB writes at the client layer; `assertEnvironmentSafety()` enforces dev isolation; Phase 0 starts `trading_bot_dev` (`5433`) and runs `data-pipeline` against QA Mongo via `MONGODB_READ_URI`. - -- **What I found (`[Verified: repo]`):** - 1. **Dev PostgreSQL init scripts (`01`–`05`) hardcode `\c trading_bot;` — leaving `trading_bot_dev` with ZERO master tables:** - - `database/postgres/init/01-init-database.sql:5-9` runs `CREATE DATABASE trading_bot` and `\c trading_bot;`, and `02-master-schema.sql:3`, `03-initial-data.sql:2`, `04-provider-exchange-mapping-schema.sql:3`, and `05-add-visible-column.sql:3` all execute `\c trading_bot;`! Meanwhile `06`–`33` omit `\c` and run in `POSTGRES_DB` (`trading_bot_dev`). On a fresh `docker-compose.dev.yml` volume, `exchanges`, `symbols`, `provider_mappings`, `provider_exchange_mappings`, and `sync_status` are created in an unused `trading_bot` DB, so `data-pipeline` connecting to `trading_bot_dev` immediately crashes on missing tables! - 2. **`MongoDBClient` `readOnly: true` is bypassed by `getDatabase()` / `collection()`, and `data-pipeline` has an active MongoDB write handler:** - - `libs/data/mongodb/src/client.ts:195-202, 384-395, 637-639, 682-684` (`getDatabase()`, `getDb()`, `database`, `getCollection()`, `collection()`) return unwrapped native `mongodb` driver objects with zero `assertWritable()` checks! - - `apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts:73-128` calls `mongoClient.getDatabase().collection('masterExchanges').updateOne(...)` and `.insertOne(...)`! - - Worse, `apps/stock/config/src/env-safety.ts:86-94` only emits `logger.warn` (does **not** throw!) if `development` `dataPipeline` connects to QA MongoDB as `trading_admin`, and `isQaMongoTarget` (`lines 43-47`) returns `false` if `MONGODB_URI` omits `/stock` in the URL path (`mongodb://localhost:27017?authSource=admin`)! - 3. **Live third-party credentials committed in source missed by `audit:secrets` + scheduled ingestion auto-start:** - - `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` hardcodes a live rotating Webshare proxy URL with username/password, and `docs/data-sources.md:15` contains a plaintext Alpha Vantage key. - - Starting `data-ingestion` runs scheduled background crawls automatically unless `QUEUE_ENABLE_SCHEDULED_JOBS=false` (verified live when `teCountries.updated_at` advanced on container boot). - -- **Recommendation:** Add four mandatory items to **Phase 0** before touching Phase A: **(1)** strip `CREATE DATABASE trading_bot` and `\c trading_bot;` from `database/postgres/init/01..05.sql`; **(2)** throw in `MongoDBClient.getDatabase()`/`collection()` when `readOnly: true` (or proxy read-only collections), delete legacy `sync-ib-exchanges.operations.ts`, and make `assertEnvironmentSafety()` **throw** if `dataPipeline` targets port `27017` without `readOnly` or with `trading_admin`; **(3)** rotate and remove the hardcoded Webshare proxy credential in `ib/shared/config.ts:19` (and `docs/data-sources.md:15`) and add `http://user:pass@` URL patterns to `scripts/audit-secrets.ts`; **(4)** default `QUEUE_ENABLE_SCHEDULED_JOBS=false` outside explicit ingestion worker deployments. - ---- - -### F8 [HIGH — Live Execution & Drift (§13)] — Missing Live Bar Architecture, Confounded Drift Monitoring, Unbounded $O(N)$ Paper State Replay, and IBKR USD/CAD + TSX Microstructure Gaps - -- **What the plan says (§13 lines 600–615):** - - Extend existing restart-safe paper host to multi-strategy/multi-asset → add IB adapter (TWS/IB Gateway) for US + Canada → OMS, continuous reconciliation, per-strategy/global risk, *"Live vs backtest tracking error on the same bars; auto-demote when outside bounds"*, and *"USD and CAD accounts/positions; base-currency P&L"*. - -- **What I found (`[Verified: repo]` + `[Verified: external — IBKR API]`):** - 1. **Zero IB API code exists in the repo, and `paper-host` has 4 concrete defects today:** - - Only a `@Disabled()` Playwright marketing-page scraper exists (`apps/stock/data-ingestion/src/handlers/ib/`), which also writes to `ib_symbols` instead of `ibSymbols` (`fetch-symbols.action.ts:108`). - - **`O(N)` genesis replay per quote (`apps/stock/engine/src/api/paper.rs:68-125`):** `stage_financial_transaction` is stateless across NAPI; on **every single quote**, it loads the entire uncompacted `simulation_accounts.state` JSONB from Postgres and replays every `MatchingReceipt` and `RiskReceipt` **from account genesis twice** (`MatchingAccount::restore` at line 75 + `RiskAccount::restore` at line 95)! Over weeks of 1m/quote paper trading, every tick grows linearly slower until timeouts trip. - - **Backtest vs. Paper execution-mode split:** Backtest `Replay` rejects `ExecutionMode::Quote` (`replay.rs:360-361`, forcing `Open`), whereas `validatePaperConfiguration` rejects `ExecutionMode::Open` (`paper-configuration.ts:36-37`, forcing `Quote` and requiring every pushed HTTP frame to end with an L1 `quote`, `feed.ts:370-372`). - - **Bar-revision crash & missing reset/sandbox:** `CanonicalPaperRuntime` (`feed.ts:158-161`, `CanonicalPaperRuntime.ts:344-349`) throws a fatal `conflict` if a bar is revised; `api/paper.rs:20-32` omits `MatchingReset` (so a drawdown halt can never be operator-reset via NAPI); and `paper-host.ts:34-37` loads promoted candidate JS **unsandboxed** inside the privileged orchestrator process! - 2. **Source of live IB bars & why they systematically diverge from EOD/QM bars:** - - IB `reqRealTimeBars` emits **5-second bars only** (`whatToShow="TRADES"` required for non-zero volume) and shares IBKR's **100 concurrent market-data line cap** (and 60 req / 10 min pacing limit) with L1 `reqMktData` quote streams! Meanwhile `reqHistoricalData(..., keepUpToDate=True)` mutates forming bars in place, sends no explicit bar-closed event, revises just-closed bars on late prints, and silently dies during IBKR's nightly ~21:00 ET server reset. - - **Vendor vs. IB bar divergence:** IBKR `SMART` `TRADES` filters out away-from-NBBO, combo, contingent, and certain off-exchange/odd-lot prints included in US SIP / TMX consolidated EOD & QM feeds (so IB bar volume is systematically lower and H/L wicks differ), and primary opening/closing crosses (`15:50 ET` NYSE/Nasdaq MOC cutoff; **`15:40 ET` TSX MOC cutoff**) differ between `SMART` and `primaryExchange`. Comparing live IB P&L against a backtest rerun on EOD/QM bars **confounds feed divergence with execution drift**! - 3. **USD/CAD & Canadian market-structure traps on IBKR:** - - **Margin vs. Cash FX:** On an **IBKR Margin account**, buying USD stocks in a CAD-funded account **does NOT auto-convert currency** — it creates a **negative USD cash balance (a margin loan accruing daily USD interest)**! On a Cash account, auto-conversion charges ~3 bps markup. Explicit programmatic FX conversion must route to **`exchange="FXCONV"`** (`secType="CASH"`, `USD.CAD`, $2 min), **never `IDEALPRO`** (which creates a virtual `USD.CAD` FX position in `positions()` that breaks reconciliation!). Both US and CA equities + `USD.CAD` settle `T+1`, except across mismatched US/CA bank holidays (Thanksgiving, Victoria Day, Civic Holiday, Boxing Day). - - **Interlisted routing & TSX/TSXV board lots:** Interlisted stocks (`SHOP`, `RY`, `TD`, `CNQ`) **must** pin `conid` + `currency` + `primaryExchange` (`TSE` vs `NYSE`) so `SMART` never routes across the border. And TSX/TSXV enforce price-tiered **Standard Trading Units (Board Lots)**: **`100` shares ($\ge \$1.00$)**, **`500` shares ($\$0.10\text{–}\$0.995$)**, **`1,000` shares ($<\$0.10$)** — whereas current `wholeShareTarget` (`canonical-sma.ts:148`) sizes to 1-share integers, generating odd-lot/mixed-lot orders routed to Canadian odd-lot dealers with inferior resting fill semantics! - -- **Recommendation:** - 1. **Build a dedicated IB Gateway Market Data & OMS Bridge service** (speaking TWS socket API to headless `IB Gateway` managed by `IBC` on the isolated `9900K` box per `docs/servers.md`): aggregate `reqRealTimeBars(5s, TRADES)` + L1 `reqMktData` quotes into session-aligned bars emitted **only after bar-close + 2s grace** (so `CanonicalPaperRuntime` never sees mid-bar mutations), capped to $\le 80$ active symbols without quote boosters (or run daily strategies off scheduled post-close/pre-open snapshots). - 2. **Split Drift Monitoring into two orthogonal checks:** - - **Engine/Execution Drift:** Live IB fills vs. Rust backtest replay on the **exact recorded IB live bars & quotes** (isolates slippage, partial fills, latency, and OMS bugs). - - **Feed Basis Drift:** Rust replay on **recorded IB bars** vs. Rust replay on **ingested EOD/QM bars** for the same dates (isolates SIP vs. IB `SMART` bar/volume divergence). - 3. **Fix Rust `Ledger` & `paper.rs` before multi-strategy paper:** Compact `simulation_accounts` checkpoints (periodic snapshot + tail receipts instead of $O(N)$ genesis replay), expose `MatchingReset`, model per-currency cash buckets `BTreeMap` with explicit `FXCONV` rebalance policy (or daily IB margin-interest accrual if intentionally borrowing), pin `conid + currency + primaryExchange` from the security master, and enforce TSX/TSXV board-lot rounding (`100`/`500`/`1000`) in position sizing. - ---- - -### F9 [MEDIUM — PostgreSQL Migrations (§18 Q2)] — `web-api`'s `migration-runner.ts` Cannot Be Reused As-Is for `data-pipeline` - -- **What the plan says (§18 line 713):** - - *"How are schema changes applied to existing PostgreSQL volumes? Recommendation: reuse `apps/stock/web-api/src/migrations/migration-runner.ts` for master tables instead of init SQL only."* - -- **What I found (`[Verified: repo]`):** - - `apps/stock/web-api/src/migrations/migration-runner.ts:9-102` uses a solid transaction-pinned advisory lock (`pg_advisory_xact_lock(0x53544254, 1)`), **but** has four blockers: **(1)** importing from `apps/stock/web-api` into `apps/stock/data-pipeline` violates the `CL26` cross-app import gate (`scripts/test/shared-runtime.test.ts:13-24`), while `libs/data/postgres/src/index.ts:12` still has `// TODO: Implement migrations`; **(2)** `migration-runner.ts:48-77` hardcodes an exact `===` filename allowlist (`09`–`33`) duplicated across 3 test files (`test/postgres/migration-runner.test.ts:13-39`, etc.); **(3)** `09-backtest-run-contract.sql` crashes on standalone `data-pipeline` test schemas (`test/postgres/pipeline-safety.test.ts`) where `06..08` (`backtests`/`runs`) weren't pre-created; and **(4)** `PipelineSyncRepository.ts:19` uses a *different* advisory lock key (`0x73746274`). - -- **Recommendation:** Extract `runMigrations` into `@stock-bot/postgres` (`libs/data/postgres`), fix `\c trading_bot;` in `01..05.sql`, split migrations into two ordered tracks (`master` DDL `02..05 + security_master` vs `research` DDL `06..33+`) using idempotent baseline guards (`CREATE TABLE IF NOT EXISTS` for `02..08`), and expose `bun run db:migrate` so both `data-pipeline` and `web-api` apply only pure fast DDL on startup. - ---- - -### F10 [MEDIUM — Agent Knowledge Base & Web App (§12, §14)] — Unnecessary Duplication of Studio's 83-Card Quant Library, Plus Misstated `web-app` Baseline - -- **What the plan says (§12 lines 556–566, 589; §14 lines 638–648):** - - Build a Knowledge Base in Stock Bot *"modeled on Studio's cards: Methods, Known anomalies and their literature, Your verified findings and dead ends, Data caveats"* that *"can feed Studio's quant library."* - - Evolve `dashboard → Home`, `research/experiments/backtest → Lab + Strategies + Agents`, `charts → Shared chart components`. - -- **What I found (`[Verified: repo]`):** - 1. **`/home/boki/repos/studio/catalog/quant/library/library.yml` already contains 83 curated quant cards across 12 sections** (`validation`, `alphas`, `features`, `statistics` [DSR, BH-FDR, White's Reality Check, Newey-West], `ml`, `regimes`, `pitfalls` [PBO, look-ahead, survivorship], `portfolio`, `risk`, `microstructure`, `execution`, `live-ops`). Maintaining a second copy of generic quant methods/literature in Stock Bot creates guaranteed two-way sync rot. - 2. **`web-app` baseline discrepancies (`29,590` LOC):** - - `apps/stock/web-app/src/features/dashboard` is an **empty directory (`0` files)** removed in `CL24` (`App.tsx:27-28` redirects `/` to `/backtests`) — `Home` is greenfield, not an evolution of `dashboard`. - - Conversely, `ResearchAgentsPage.tsx` (`377` LOC at `/research/agents`, `App.tsx:55`) and `StoredSourceInspector.tsx` (`364` LOC) **already exist** today (though `/research/agents` is missing from `Sidebar.tsx`!), and **two separate chart stacks** exist (`src/components/charts/Chart.tsx` vs `src/features/charts/components/SymbolChart.tsx`). - - Also minor repo-state inaccuracies in §2 & §3: `studio.config.json:34-42` points to nonexistent `design/*` and `docs/marketing/brand.md`; actual backlog completion after E13 (`CL22–CL35`, `docs/development/backlog/README.md:3-15`) is **113 done / 5 deferred / 4 merged = 122 IDs** (not `99/5/4 = 108`); and §2 `lint:check` (`line 85`) is `61` in `phase1-inventory.ts` (`59` errors + `2` warnings) + **`4`** in WIP files = `65` (not `61 + 7`). - -- **Recommendation:** Mount/read Studio's `catalog/quant/library/library.yml` directly as read-only methodology/literature context in the MCP server, and store **only empirical Stock Bot artifacts** (`findings`, `dead_ends`, and `provider_caveats` linked to run/signal hashes) in PostgreSQL. In `web-app`, wire existing `/research/agents` into `Sidebar.tsx`, unify the two `lightweight-charts` wrappers before building Lab screens, and defer greenfield `Home` + `Markets` until after Signal Lab and Portfolio Backtest v2 work. - ---- - -### F11 [MEDIUM — marimo Integration Details (D9 & §11)] — Cookie/Origin Isolation, Kernel RAM Pinning, and `MB002` Agent Codegen Failures - -- **What the plan says (§3 D9, §11 lines 507–539):** - - Agents write `research/notebooks/*.py`; `marimo edit` for your sessions on localhost behind the app's auth; `marimo run` / static HTML for agent findings embedded in the App `Lab` tab. - -- **What I found (`[Verified: external — marimo docs]` + `[Verified: repo]`):** - 1. **Same-origin `