Compare commits
24 commits
master
...
data-servi
| Author | SHA1 | Date | |
|---|---|---|---|
| 5ded78f8e4 | |||
| 54314a0cde | |||
| 3097686849 | |||
| d9bd33a822 | |||
| 07f8964a8c | |||
| eeae192872 | |||
| 9d38f9a7b6 | |||
| 8955544593 | |||
| 24b7ed15e4 | |||
| be807378a3 | |||
| 16599c86da | |||
| b645b58102 | |||
| 709fc347e9 | |||
| 423b40866c | |||
| aed5ff3d98 | |||
| 84e6dee53f | |||
| 4aa2942e43 | |||
| 35b0eb3783 | |||
| a7ec942916 | |||
| ed326c025e | |||
| 47ff92b567 | |||
| 2f074271cc | |||
| df611a3ce3 | |||
| b49bea818b |
1538 changed files with 41734 additions and 329372 deletions
|
|
@ -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"
|
|
||||||
}
|
|
||||||
54
.env
54
.env
|
|
@ -4,22 +4,16 @@
|
||||||
|
|
||||||
# Core Application Settings
|
# Core Application Settings
|
||||||
NODE_ENV=development
|
NODE_ENV=development
|
||||||
LOG_LEVEL=debug
|
LOG_LEVEL=info
|
||||||
LOG_HIDE_OBJECT=true
|
|
||||||
|
|
||||||
STOCK_BOT_ADMIN_TOKEN=ae8da49a63295865ff9e3d0b4ec012e3ccea73a56d3ff76ae6c7276d9d539ed3
|
|
||||||
STOCK_BOT_SERVICE_TOKEN=df6510947397dff96078f0b330c82779aff741583e862069c0e37a2be14a4f03
|
|
||||||
|
|
||||||
# Data Service Configuration
|
# Data Service Configuration
|
||||||
DATA_SERVICE_PORT=2001
|
DATA_SERVICE_PORT=2001
|
||||||
|
|
||||||
# Queue and Worker Configuration
|
# Queue and Worker Configuration
|
||||||
WORKER_COUNT=1
|
WORKER_COUNT=4
|
||||||
WORKER_CONCURRENCY=2
|
WORKER_CONCURRENCY=20
|
||||||
|
|
||||||
WEBSHARE_API_KEY=
|
WEBSHARE_API_KEY=y8ay534rcbybdkk3evnzmt640xxfhy7252ce2t98
|
||||||
WEBSHARE_ROTATING_PROXY_URL=
|
|
||||||
WEBSHARE_API_URL=https://proxy.webshare.io/api/v2/
|
|
||||||
|
|
||||||
# ===========================================
|
# ===========================================
|
||||||
# DATABASE CONFIGURATIONS
|
# DATABASE CONFIGURATIONS
|
||||||
|
|
@ -27,31 +21,31 @@ WEBSHARE_API_URL=https://proxy.webshare.io/api/v2/
|
||||||
|
|
||||||
# Dragonfly/Redis Configuration
|
# Dragonfly/Redis Configuration
|
||||||
DRAGONFLY_HOST=localhost
|
DRAGONFLY_HOST=localhost
|
||||||
DRAGONFLY_PORT=6380
|
DRAGONFLY_PORT=6379
|
||||||
DRAGONFLY_PASSWORD=
|
DRAGONFLY_PASSWORD=
|
||||||
|
|
||||||
# PostgreSQL Configuration
|
# PostgreSQL Configuration
|
||||||
POSTGRES_HOST=localhost
|
POSTGRES_HOST=localhost
|
||||||
POSTGRES_PORT=5433
|
POSTGRES_PORT=5432
|
||||||
POSTGRES_DATABASE=trading_bot_dev
|
POSTGRES_DB=stockbot
|
||||||
POSTGRES_USERNAME=dev_user
|
POSTGRES_USER=postgres
|
||||||
POSTGRES_PASSWORD=dev_pass
|
POSTGRES_PASSWORD=postgres
|
||||||
POSTGRES_SSL=false
|
POSTGRES_SSL=false
|
||||||
|
|
||||||
# QuestDB Configuration
|
# QuestDB Configuration
|
||||||
QUESTDB_HOST=localhost
|
QUESTDB_HOST=localhost
|
||||||
QUESTDB_PORT=9100
|
QUESTDB_PORT=9000
|
||||||
QUESTDB_DB=qdb
|
QUESTDB_DB=qdb
|
||||||
QUESTDB_USERNAME=admin
|
QUESTDB_USER=admin
|
||||||
QUESTDB_PASSWORD=quest
|
QUESTDB_PASSWORD=quest
|
||||||
|
|
||||||
# MongoDB Configuration
|
# MongoDB Configuration
|
||||||
MONGODB_HOST=localhost
|
MONGODB_HOST=localhost
|
||||||
MONGODB_PORT=27018
|
MONGODB_PORT=27017
|
||||||
MONGODB_DATABASE=stock_dev
|
MONGODB_DB=stockbot
|
||||||
MONGODB_USERNAME=dev_admin
|
MONGODB_USER=
|
||||||
MONGODB_PASSWORD=dev_mongo_pass
|
MONGODB_PASSWORD=
|
||||||
MONGODB_URI=mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin
|
MONGODB_URI=mongodb://localhost:27017/stockbot
|
||||||
|
|
||||||
# ===========================================
|
# ===========================================
|
||||||
# DATA PROVIDER CONFIGURATIONS
|
# DATA PROVIDER CONFIGURATIONS
|
||||||
|
|
@ -154,6 +148,7 @@ SOURCE_MAPS=true
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
# Docker-specific settings (used in docker-compose)
|
# Docker-specific settings (used in docker-compose)
|
||||||
|
COMPOSE_PROJECT_NAME=stock-bot
|
||||||
DOCKER_BUILDKIT=1
|
DOCKER_BUILDKIT=1
|
||||||
|
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
@ -164,17 +159,6 @@ DOCKER_BUILDKIT=1
|
||||||
TZ=UTC
|
TZ=UTC
|
||||||
|
|
||||||
# Application Metadata
|
# Application Metadata
|
||||||
APP_NAME="Stock Bot Platform"
|
APP_NAME=Stock Bot Platform
|
||||||
APP_VERSION=1.0.0
|
APP_VERSION=1.0.0
|
||||||
APP_DESCRIPTION="Advanced Stock Trading and Analysis Platform"
|
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
|
|
||||||
|
|
|
||||||
242
.env.complete
Normal file
242
.env.complete
Normal file
|
|
@ -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
|
||||||
|
|
@ -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:<QA_READ_PASSWORD>@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
|
|
||||||
144
.env.docker
Normal file
144
.env.docker
Normal file
|
|
@ -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
|
||||||
58
.env.example
58
.env.example
|
|
@ -1,17 +1,43 @@
|
||||||
# Generate each token independently: openssl rand -hex 32
|
# Environment Configuration
|
||||||
# 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
|
|
||||||
NODE_ENV=development
|
NODE_ENV=development
|
||||||
# Provider credentials are optional; configure only the providers you enable.
|
PORT=3000
|
||||||
EOD_API_KEY=
|
|
||||||
QM_USERNAME=
|
# Database Configuration
|
||||||
QM_PASSWORD=
|
QUESTDB_HOST=localhost
|
||||||
IB_ACCOUNT=
|
QUESTDB_PORT=9000
|
||||||
IB_PROXY_URL=
|
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
|
||||||
|
|
|
||||||
233
.env.prod
Normal file
233
.env.prod
Normal file
|
|
@ -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
|
||||||
|
|
@ -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=
|
|
||||||
135
.env.production
Normal file
135
.env.production
Normal file
|
|
@ -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
|
||||||
|
|
@ -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:<QA_READ_PASSWORD>@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
|
|
||||||
81
.eslintignore
Normal file
81
.eslintignore
Normal file
|
|
@ -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
|
||||||
228
.gitignore
vendored
228
.gitignore
vendored
|
|
@ -1,123 +1,105 @@
|
||||||
# Environment files (the two private local-development configs are intentionally tracked)
|
# Dependencies
|
||||||
.env
|
node_modules/
|
||||||
.env.*
|
.pnp
|
||||||
!/.env
|
.pnp.js
|
||||||
!/apps/stock/web-app/.env
|
|
||||||
!.env.example
|
# Production builds
|
||||||
!.env.*.example
|
dist/
|
||||||
|
build/
|
||||||
# Dependencies
|
.next/
|
||||||
node_modules/
|
*.js.map
|
||||||
.pnp
|
*.d.ts
|
||||||
.pnp.js
|
|
||||||
|
|
||||||
# Production builds
|
# Logs
|
||||||
dist/
|
npm-debug.log*
|
||||||
build/
|
yarn-debug.log*
|
||||||
.next/
|
yarn-error.log*
|
||||||
*.js.map
|
bun-debug.log*
|
||||||
*.d.ts
|
bun-error.log*
|
||||||
!apps/stock/engine/index.d.ts
|
*.log
|
||||||
|
|
||||||
|
# Runtime data
|
||||||
# Logs
|
pids
|
||||||
npm-debug.log*
|
*.pid
|
||||||
yarn-debug.log*
|
*.seed
|
||||||
yarn-error.log*
|
*.pid.lock
|
||||||
bun-debug.log*
|
*.tsbuildinfo
|
||||||
bun-error.log*
|
|
||||||
*.log
|
# Coverage directory used by tools like istanbul
|
||||||
|
coverage/
|
||||||
# Runtime data
|
*.lcov
|
||||||
pids
|
|
||||||
*.pid
|
# Dependency directories
|
||||||
*.seed
|
.pnpm-store/
|
||||||
*.pid.lock
|
|
||||||
*.tsbuildinfo
|
# Optional npm cache directory
|
||||||
|
.npm
|
||||||
# Coverage directory used by tools like istanbul
|
|
||||||
coverage/
|
# Optional eslint cache
|
||||||
*.lcov
|
.eslintcache
|
||||||
|
|
||||||
# Dependency directories
|
# Optional stylelint cache
|
||||||
.pnpm-store/
|
.stylelintcache
|
||||||
|
|
||||||
# Optional npm cache directory
|
# Microbundle cache
|
||||||
.npm
|
.rpt2_cache/
|
||||||
|
.rts2_cache_cjs/
|
||||||
# Optional eslint cache
|
.rts2_cache_es/
|
||||||
.eslintcache
|
.rts2_cache_umd/
|
||||||
|
|
||||||
# Optional stylelint cache
|
# Optional REPL history
|
||||||
.stylelintcache
|
.node_repl_history
|
||||||
|
|
||||||
# Microbundle cache
|
# Output of 'npm pack'
|
||||||
.rpt2_cache/
|
*.tgz
|
||||||
.rts2_cache_cjs/
|
|
||||||
.rts2_cache_es/
|
# Yarn Integrity file
|
||||||
.rts2_cache_umd/
|
.yarn-integrity
|
||||||
|
|
||||||
# Optional REPL history
|
# parcel-bundler cache (https://parceljs.org/)
|
||||||
.node_repl_history
|
.cache
|
||||||
|
.parcel-cache
|
||||||
# Output of 'npm pack'
|
|
||||||
*.tgz
|
# Next.js build output
|
||||||
|
.next
|
||||||
# Yarn Integrity file
|
|
||||||
.yarn-integrity
|
# Nuxt.js build / generate output
|
||||||
|
.nuxt
|
||||||
# parcel-bundler cache (https://parceljs.org/)
|
|
||||||
.cache
|
# Storybook build outputs
|
||||||
.parcel-cache
|
.out
|
||||||
|
.storybook-out
|
||||||
# Next.js build output
|
|
||||||
.next
|
# Temporary folders
|
||||||
|
tmp/
|
||||||
# Nuxt.js build / generate output
|
temp/
|
||||||
.nuxt
|
|
||||||
|
# Editor directories and files
|
||||||
# Storybook build outputs
|
.idea/
|
||||||
.out
|
*.swp
|
||||||
.storybook-out
|
*.swo
|
||||||
|
*~
|
||||||
# Temporary folders
|
|
||||||
tmp/
|
# OS generated files
|
||||||
temp/
|
.DS_Store
|
||||||
|
.DS_Store?
|
||||||
# Editor directories and files
|
._*
|
||||||
.idea/
|
.Spotlight-V100
|
||||||
*.swp
|
.Trashes
|
||||||
*.swo
|
ehthumbs.db
|
||||||
*~
|
Thumbs.db
|
||||||
|
|
||||||
# OS generated files
|
# Trading bot specific
|
||||||
.DS_Store
|
.data/
|
||||||
.DS_Store?
|
.backtest-results/
|
||||||
._*
|
.logs/
|
||||||
.Spotlight-V100
|
.old/
|
||||||
.Trashes
|
.mongo/
|
||||||
ehthumbs.db
|
.chat/
|
||||||
Thumbs.db
|
*.db
|
||||||
|
*.sqlite
|
||||||
# Trading bot specific
|
*.sqlite3
|
||||||
.data/
|
|
||||||
.backtest-results/
|
# Turbo
|
||||||
.logs/
|
.turbo
|
||||||
.old/
|
|
||||||
.mongo/
|
|
||||||
.chat/
|
|
||||||
*.db
|
|
||||||
*.sqlite
|
|
||||||
*.sqlite3
|
|
||||||
|
|
||||||
# Turbo
|
|
||||||
.turbo
|
|
||||||
*.tsbuildinfo
|
|
||||||
|
|
||||||
# AI
|
|
||||||
.serena/
|
|
||||||
.claude/
|
|
||||||
docs/configuration-standardization.md
|
|
||||||
|
|
||||||
# Rust
|
|
||||||
target/
|
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,19 @@
|
||||||
stages:
|
stages:
|
||||||
- build
|
- build
|
||||||
- test
|
- test
|
||||||
- deploy
|
- deploy
|
||||||
- review
|
- review
|
||||||
- dast
|
- dast
|
||||||
- staging
|
- staging
|
||||||
- canary
|
- canary
|
||||||
- production
|
- production
|
||||||
- incremental rollout 10%
|
- incremental rollout 10%
|
||||||
- incremental rollout 25%
|
- incremental rollout 25%
|
||||||
- incremental rollout 50%
|
- incremental rollout 50%
|
||||||
- incremental rollout 100%
|
- incremental rollout 100%
|
||||||
- performance
|
- performance
|
||||||
- cleanup
|
- cleanup
|
||||||
sast:
|
sast:
|
||||||
stage: test
|
stage: test
|
||||||
include:
|
include:
|
||||||
- template: Auto-DevOps.gitlab-ci.yml
|
- 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
|
|
||||||
|
|
|
||||||
21
.prettierrc
21
.prettierrc
|
|
@ -10,9 +10,7 @@
|
||||||
"bracketSpacing": true,
|
"bracketSpacing": true,
|
||||||
"bracketSameLine": false,
|
"bracketSameLine": false,
|
||||||
"quoteProps": "as-needed",
|
"quoteProps": "as-needed",
|
||||||
"plugins": [
|
"plugins": ["@ianvs/prettier-plugin-sort-imports"],
|
||||||
"@ianvs/prettier-plugin-sort-imports"
|
|
||||||
],
|
|
||||||
"importOrder": [
|
"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)$",
|
"^(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)$",
|
||||||
"<THIRD_PARTY_MODULES>",
|
"<THIRD_PARTY_MODULES>",
|
||||||
|
|
@ -24,20 +22,5 @@
|
||||||
"^\\.(?!/?$)",
|
"^\\.(?!/?$)",
|
||||||
"^\\./?$"
|
"^\\./?$"
|
||||||
],
|
],
|
||||||
"importOrderParserPlugins": [
|
"importOrderParserPlugins": ["typescript", "decorators-legacy"]
|
||||||
"typescript",
|
|
||||||
"decorators-legacy"
|
|
||||||
],
|
|
||||||
"overrides": [
|
|
||||||
{
|
|
||||||
"files": "**/*.tsx",
|
|
||||||
"options": {
|
|
||||||
"importOrderParserPlugins": [
|
|
||||||
"typescript",
|
|
||||||
"jsx",
|
|
||||||
"decorators-legacy"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
3
.vscode/mcp.json
vendored
3
.vscode/mcp.json
vendored
|
|
@ -1,3 +0,0 @@
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
48
AGENTS.md
48
AGENTS.md
|
|
@ -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).
|
|
||||||
34
CLAUDE.md
34
CLAUDE.md
|
|
@ -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.
|
|
||||||
1658
Cargo.lock
generated
1658
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
29
Cargo.toml
29
Cargo.toml
|
|
@ -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
|
|
||||||
377
DEVELOPMENT-ROADMAP.md
Normal file
377
DEVELOPMENT-ROADMAP.md
Normal file
|
|
@ -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<Quote>;
|
||||||
|
getHistorical(symbol: string, period: TimePeriod): Promise<OHLCV[]>;
|
||||||
|
isHealthy(): Promise<boolean>;
|
||||||
|
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<T = number> {
|
||||||
|
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
|
||||||
758
README.md
758
README.md
|
|
@ -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_<interval>.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 <token>`. 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:<type>"`.
|
|
||||||
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.
|
|
||||||
402
REVIEW.md
402
REVIEW.md
|
|
@ -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: <number> }]` 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/<name>/v<k>.py|.sql`) that write `(listing_id, ts, known_at, value: f64)` to the `features` store. Add a read-only `features: Record<string, number | null>` 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<Currency, Posting>` 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 `<iframe>` steals operator session cookies:** `web-api` issues `stock_bot_session` (`HttpOnly; SameSite=Strict`, `libs/core/di/src/http/security.ts:254`). If `marimo` is reverse-proxied under `web-app`'s origin with `<iframe sandbox="allow-scripts allow-same-origin">`, JavaScript in an agent-authored notebook widget can call `/api/v2/paper-deployments` or `/api/v2/research-agents` as `'operator'`!
|
|
||||||
2. **Per-tab Python kernel memory pinning:** Both `marimo edit` and `marimo run` spawn 1 Python process per open browser session and keep all global cell variables pinned in RAM to power reactive downstream cells (easily 1–3 GB per Polars tab).
|
|
||||||
3. **LLM `MB002` (`multiple-definitions`) trap:** Unprimed LLMs write `df = ...` or `fig = ...` across multiple cells, which marimo's static DAG compiler hard-rejects (`MB002`). Fortunately, `marimo check --format=json file.py` validates the entire AST/DAG statically in milliseconds without starting a kernel, and `marimo edit --mcp` gives desktop Claude Code live read-only cell inspection.
|
|
||||||
|
|
||||||
- **Recommendation:** Confirm **D9 (marimo)** with four concrete implementation rules: **(1)** render Agent Lab Feed notebooks as **static HTML snapshots (`marimo export html`)** in `<iframe sandbox="allow-scripts" srcDoc={...}>` (zero RAM, no `allow-same-origin`), spinning up `marimo run --session-ttl 300` on a **separate port/origin** only on explicit *"Open interactive"* click; **(2)** run your `marimo edit ./research/notebooks --watch --mcp` on a dedicated loopback port (`127.0.0.1:2718`) with token auth; **(3)** inject marimo's official agent rules (`_df` underscore-prefixed cell-local variables to free Polars memory immediately) into agent prompts and gate every agent notebook write on `marimo check --format=json` exit code `0`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Section 18 Open Questions — Answers & Recommended Defaults
|
|
||||||
|
|
||||||
| # | Section 18 Question | Answer from Repo / Data & Recommended Default |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| **Q1** | *Which MongoDB login does routine pipeline work use (`studio_stock_bot_read` vs `trading_admin`)?* | **`[Verified: QA Mongo & repo]`** `studio_stock_bot_read@stock` (`role: read@stock`) **already exists** in QA MongoDB (`phase1-investigation.md:116`, verified live). **Default:** Use `studio_stock_bot_read` via `MONGODB_READ_URI` for **all** `data-pipeline` runs in `dev`, `qa`, and `prod` (provision an identical `read@<db>` user on dev `27018/stock_dev` and prod). Only `data-ingestion` ever receives `trading_admin` / readWrite credentials. Make `assertEnvironmentSafety()` throw if `dataPipeline` uses `trading_admin`. |
|
|
||||||
| **Q2** | *How are schema changes applied to existing PostgreSQL volumes?* | **`[Verified: repo]`** Do **not** import `web-api`'s `migration-runner.ts` directly (violates `CL26` and fails on `\c trading_bot;` in `01..05.sql` — see Finding F9). **Default:** Move `runMigrations` to `@stock-bot/postgres`, strip `\c trading_bot;` from `01..05.sql`, replace the hardcoded filename allowlist with checksum-verified numbered SQL migrations split into `master` and `research` tracks, and run via `bun run db:migrate` + service startup. |
|
|
||||||
| **Q3** | *Is marimo confirmed for the Lab (D9)?* | **Yes — confirm D9**, using static HTML export for the Agent Feed, separate-origin `127.0.0.1:2718` (`--watch --mcp`) for `marimo edit`, `_`-prefixed local variables, and mandatory `marimo check` gating (see Finding F11). |
|
|
||||||
| **Q4** | *Exact storage exit-criteria numbers (Section 5) — confirm or adjust?* | **Adjust to include row/universe counts and cold vs. warm cache** (vague workloads invite cherry-picked benchmarks):<br>• **W1 (20y US+CA daily scan + 1 signal IC/quantiles, ~15k active+delisted listings / ~45M bars):** `< 3 s` warm / `< 8 s` cold (DuckDB+Parquet hits `< 2 s` on `quant`).<br>• **W2 (1 listing, 1y of `1m` regular+extended bars, ~100k–200k rows):** `< 250 ms` warm / `< 1 s` cold.<br>• **W3 (4 concurrent campaign workers):** p95 wall-time degradation `< 35%` vs. 1 worker, zero OOM / lease timeouts.<br>• **W4 (1 date cross-section, ~8k alive listings × 20 features):** `< 100 ms`. |
|
|
||||||
| **Q5** | *Which FX source for USD/CAD?* | **`[Verified: QA Mongo]`** **Already ingested!** Use `eodPrices` / `eodIntraday1M` `CAD.FOREX` (`12,109` daily bars `1971–2025` + `5.20M` `1m` bars) patched post-Aug 2025 by `teMarketData` (`USDCAD`, through `2026-04-02`), and once IB Gateway is connected in Phase F, ingest live `USD.CAD` `MIDPOINT` bars directly from IB + Bank of Canada daily noon/16:30 indicative rates for accounting reconciliation. |
|
|
||||||
| **Q6** | *Is `ttFutures` in scope, and when?* | **`[Verified: QA Mongo]`** **Out of scope now — defer indefinitely (post-Phase F).** `ttFutures` (`1.46M` docs) has corrupted date strings (`"2001-/0-2/"`, `"NaN-at-e\""`), requires continuous contract-roll splicing, point-value multipliers, and initial/maintenance margin semantics orthogonal to US/CA equities. |
|
|
||||||
| **Q7** | *Thresholds for lifecycle gates (IC, deflated Sharpe, paper duration, drift bounds)?* | **Recommended Concrete Defaults (`[Assumed]` quant calibration for US+CA daily/intraday):**<br>• **`Hypothesis → Signal`:** Mean rank IC $|\overline{\text{IC}}| \ge 0.015$ (daily, $t\text{-stat} \ge 3.0$ Newey-West) or event-study post-cost abnormal return $\ge +35\text{ bps}$ ($t \ge 3.0$), positive in $\ge 70\%$ of 2-year sub-periods.<br>• **`Signal → Candidate`:** Tier 1 post-cost Sharpe $\ge 1.0$ at $1.5\times$ baseline spread+commission, daily turnover feasible within $2\%$ ADV.<br>• **`Candidate → Validated`:** **DSR $\ge 0.95$** (using cluster $\hat{N}$ and cross-trial Sharpe variance), **PBO $\le 0.20$**, positive net Sharpe at **$2.0\times$ transaction costs**, max single-year loss within risk budget.<br>• **`Validated → Paper`:** One-shot Vault Holdout (`ts >= VAULT_CUTOFF`) Sharpe $> 0.5$ and within $1.5\sigma$ of CPCV distribution + **your manual approval**.<br>• **`Paper → Small Live`:** Minimum **30 trading days AND $\ge 50$ round-trip trades** (60 trading days for slower swing/monthly strategies); **Engine/Execution Drift** $|\text{live} - \text{IB-bar replay}| \le 15\text{ bps/trade}$ and daily return tracking error $\le 50\text{ bps annualized}$ (or $\le 25\%$ of strategy vol), zero unrecovered reconciliation breaks. |
|
|
||||||
| **Q8** | *Which hosts join the worker pool, and when?* | **`[Verified: repo — docs/servers.md + live quant specs]`** Keep **all research, pipeline, QuestDB, Postgres, MongoDB, and worker-pool slots on `quant` (`12900K`, 24 threads, 125 GiB RAM, 3.6 TiB NVMe)** through Phases 0–E — zero distributed multi-host worker complexity needed! Bring **`9900K` (8C/16T, 32 GB RAM)** online **only in Phase F** strictly as the **isolated Paper + Live IB Gateway host** (`docs/servers.md:6-17`), and use **TrueNAS MinIO** strictly for cold backups/snapshots. Keep your desktop workstation out of unattended overnight worker pools. |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Revised Roadmap (Solo-Developer Critical Path)
|
|
||||||
|
|
||||||
### Strategy: Thinnest Honest End-to-End Slice First ("Vertical Slice 1" in ~3 Weeks)
|
|
||||||
|
|
||||||
Instead of building every dataset, UI screen, QuestDB table, and multi-asset Rust extension before testing your first hypothesis, build **one narrow, completely honest vertical slice** (US+CA security master → daily bars + corporate actions + Canadian shorts/filings in DuckDB/Parquet → trial ledger + Vault cutoff → Python `stockbot` SDK + marimo Signal Analyzer). That gets you and desktop Claude Code hunting real cross-sectional & alt-data edges by **Week 3**, while heavy Rust multi-asset refactoring follows *only* once you have validated signals worth trading as portfolios.
|
|
||||||
|
|
||||||
### Explicit Cuts & Deferrals
|
|
||||||
1. **Cut** the dual-backend QuestDB↔DuckDB parity harness (use DuckDB+Parquet directly for daily/PIT/features; QuestDB `10.2.0` for `1m` intraday).
|
|
||||||
2. **Cut** `eodFundamentalsOLD` snapshots from backtesting and **cut** macro-release event studies on `teData` (physically unsupported by the raw data).
|
|
||||||
3. **Cut** `ttFutures` from scope.
|
|
||||||
4. **Defer** Pass 5 Merge Review Web UI in Slice 1 — generate a markdown/CSV conflict report + SQL `override` seed file (~320 exchanges + top symbol conflicts take <2 hours to review in an editor vs. weeks of React CRUD).
|
|
||||||
5. **Defer** a custom Knowledge Base DB/UI — serve `~/repos/studio/catalog/quant/library/library.yml` (83 cards) read-only via MCP + one `findings` table in Postgres.
|
|
||||||
6. **Defer** multi-host distributed scheduling (`quant`'s 24 threads + 125 GiB RAM handle 8–12 local workers on one machine) and defer greenfield `Home` & `Markets` dashboards until Phase E.
|
|
||||||
|
|
||||||
### Phased Sequence & Sharp Exit Criteria
|
|
||||||
|
|
||||||
| Phase | Scope | Sharp, Falsifiable Exit Criteria |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| **0. Safety & Gate Lock** *(2–3 days)* | • Fix `workspace.test.ts` & `lint:check` (65 issues), delete 6 stray root files.<br>• Strip `\c trading_bot;` from `database/postgres/init/01..05.sql`; extract `runMigrations` to `@stock-bot/postgres`.<br>• Block `MongoDBClient.getDatabase()`/`collection()` when `readOnly: true`, delete `sync-ib-exchanges.operations.ts`, make `env-safety.ts` throw on non-readonly QA Mongo, default `QUEUE_ENABLE_SCHEDULED_JOBS=false`.<br>• Rotate & purge hardcoded Webshare proxy credentials (`ib/shared/config.ts:19`) + Alpha Vantage key (`docs/data-sources.md:15`).<br>• Remove `/export` from `sb-research.*` (`research-agents.service.ts:51`) and add cumulative trial budget columns. | 1. All 11 repo gates pass (`0` errors, `0` warnings).<br>2. Automated test proves fresh `trading_bot_dev` (`5433`) has all master + research tables.<br>3. Integration test proves `data-pipeline` throws on both `client.insertOne()` **and** `client.getDatabase().collection().insertOne()`, and QA Mongo rejects writes via `studio_stock_bot_read`.<br>4. Test proves `sb-research.*` gets `403` on `/api/v2/datasets/canonical/:hash/export`. |
|
|
||||||
| **1. Vertical Slice 1: Security Master + Honest Daily/Event Signal Lab** *(Weeks 1–3)* | • **Step 1 Merge (US+CA):** Instrument-first ISIN/CUSIP + `instrument_identifier_history` + EOD/QM primary MIC (`exclude NMFQS`) + IB `conid` attached at `(instrument_id, currency)` + bar-span validity windows + 25-date cross-sectional price check + OTC delisting continuation links (`SIVB`→`SIVBQ`) + SQL `override` file.<br>• **Step 2 Core (`DuckDB + Parquet`):** Curate `bars_1d` (un-adjusting `eodPrices.volume`!), `corporate_actions` + `adj_factors` (`qmSplits`, `qmDividends`), `fx` (`CAD.FOREX` + `teMarketData.USDCAD`), `qmFilings` (`timefiled`), `qmEarnings` (lagged when `announceTime='N/A'`), and `ceoShorts` (`+4bd` lag).<br>• **MarketDataStore + Vault Air-Gap:** `VAULT_CUTOFF_DATE = '2025-01-01'` hard-enforced on non-vault reads.<br>• **Trial Ledger + Python SDK + marimo:** Postgres `trial_ledger` storing `(cluster, params, return_vector)` + DSR (`effective N_hat`) + `stockbot` Python SDK + `marimo edit` (`127.0.0.1:2718`). | 1. US+CA match report committed: `100%` of ~320 exchange rows reviewed; $\ge 95\%$ of active+delisted US/CA equities resolved with `< 0.5%` unreviewed high-cap conflicts; `FB` (2012–2022) and `FB` (2025 ETF) resolve to distinct `listing_id`s; `SIVB` links to `SIVBQ` terminal loss; `NVDA` pre-split `close * raw_volume` matches `qmPrices` within `1%`.<br>2. 20y US+CA daily universe scan + 1 signal IC/quantile/turnover/DSR runs in `< 5 s` on `quant` without touching `ts >= 2025-01-01`.<br>3. Every `analyze_signal` call writes an immutable `trial_ledger` row with return vector and increments $\hat{N}$. |
|
|
||||||
| **2. MCP Copilot + Intraday QuestDB + PIT Fundamentals** *(Weeks 4–5)* | • **MCP Server:** Expose `search_symbols`, `query_data` (vault-fenced), `analyze_signal`, `event_study`, `file_finding`, `read_knowledge` (backed by Studio's `library.yml` + Postgres `findings`) to Claude Code / Claude Desktop.<br>• **PIT Fundamentals:** Curate `qmFinancials` joined to `qmFilings` `timefiled` (+ NI 51-102/SEC statutory lag fallback) with 2D `(period_end, known_at)` deduplication + TTM wide snapshots.<br>• **Intraday (`QuestDB 10.2.0`):** Pin QuestDB Docker tag, replace broken `libs/data/questdb`, un-adjust `eodIntraday1M` splits (cross-checked against `qmIntraday` raw), load `bars_1m` (`listing_id SYMBOL CAPACITY 65536 NOCACHE`).<br>• **Versioned Feature Library:** Batch SQL/Polars feature jobs (`technical`, `cross_sectional`, `fundamental`, `short_interest`, `event`). | 1. Claude Code via MCP runs an end-to-end cross-sectional signal analysis + event study, exports a `marimo check`-clean static HTML snapshot, and files a finding.<br>2. Restatement regression test proves restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`.<br>3. `NEXM.V` and `NVDA.US` 1m vs 1d split-boundary continuity test passes with `< 0.5%` session-close discrepancy, and 1y of 1m bars for 1 listing loads in `< 500 ms`. |
|
|
||||||
| **3. Portfolio Backtest v2 (Tier 1 Screener + Tier 2 Rust Multi-Asset)** *(Weeks 6–9)* | • **Tier 1 Columnar Screener:** Fast vectorized parameter/universe screener over precomputed features, logging full $M_{T \times N}$ matrix to `trial_ledger` for PBO & DSR.<br>• **Tier 2 Rust `financial/` Upgrades:** **(a)** Atomic timestamp-slice mark updates before risk checks (`F06` fix); **(b)** simultaneous sell-proceeds netting in `StrategyIntent::Target` (`matching.rs:1083`); **(c)** `features` map in `Replay` + `StrategyContext`; **(d)** corporate-action split share adjustment + cash dividend postings + OTC/Shumway delisting liquidation; **(e)** long/short + borrow cost + multi-currency `BTreeMap<Currency, Posting>` (`USD`/`CAD` via `fx`); **(f)** Arrow/Parquet dataset loading into Rust (replacing `JSONB` snapshots) + remove double JSON parse in `api/canonical.rs`.<br>• **Validation Suite:** Purged Walk-Forward, CPCV, DSR, PBO, cost sensitivity, capacity, factor exposure, and one-shot human Vault Holdout gate. Retire legacy `BacktestEngine` and TS `SimulationExecution`. | 1. Differential fixtures pass for: atomic long/short mark neutrality, fully-invested `Sell A + Buy B` target rotation, 10:1 split + cash dividend exact 8-decimal conservation, and `SIVB` delisting loss.<br>2. Full 20y US+CA cross-sectional daily portfolio backtest (`~5,000+` listings, weekly/daily rebalance) completes in `< 30 s` in Tier 2 Rust.<br>3. A surviving signal from Phase 2 passes `Screen → Rust Engine → CPCV/DSR/PBO → Human Vault Gate` using precomputed `features` with zero indicator rewrite in TS. |
|
|
||||||
| **4. Autonomous Campaigns, Studio Bridge & Incremental Web App** *(Weeks 10–12)* | • Containerized campaign runner (`quant`) with strict per-campaign/daily trial & compute budgets, Roles (`Scout`, `Data Analyst`, `Signal Researcher`, `Strategy Builder`, `Skeptic`), and Studio Quant hypothesis → verdict webhook/API bridge.<br>• Web App (`Lab` signal/event views + static HTML marimo viewer, `Agents` feed + wired `/research/agents`, `Data` coverage/quality/conflicts, unified `charts`). | 1. Overnight containerized campaign from a Studio hypothesis runs unattended within budget, cannot reach DB ports or Vault dates, runs Skeptic checks, and posts static-HTML-backed findings to the Lab Feed.<br>2. Attempting to exceed campaign trial budget halts admission via Postgres trigger. |
|
|
||||||
| **5. Paper at Scale → Live IB (`9900K`)** *(Weeks 13–16)* | • Fix `api/paper.rs` $O(N)$ receipt replay via periodic state compaction + tail journal, add `MatchingReset`, and sandbox promoted candidate code in `paper-host` (or require explicit built-in compilation).<br>• Deploy headless `IB Gateway` + `IBC` + **IB Market Data & OMS Bridge** on isolated `9900K`: idempotent client order IDs, `conid + currency + primaryExchange` pinning, TSX/TSXV `100/500/1000` board-lot sizing, `FXCONV` cash conversion, continuous position/cash reconciliation, kill switches, and **Dual Drift Monitor** (Execution Drift + Feed Basis Drift). | 1. `paper-host` processes `100,000` sequential quotes with flat `< 5 ms` p99 latency (proving $O(1)$ compacted state).<br>2. Paper runs 30+ trading days on IB paper account across US (`USD`) + TSX (`CAD`) listings with zero unrecovered reconciliation breaks and Execution Drift `< 15 bps/trade`.<br>3. Live small-capital deployment passes kill-switch, partial-fill, nightly IB Gateway 21:00 ET reconnect, and `FXCONV` tests. |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Specific Edits to `docs/PLATFORM-PLAN.md`, by Section
|
|
||||||
|
|
||||||
- **§1 (Vision and principles, lines 44–52):**
|
|
||||||
- Principle 1: Clarify that where raw providers omit true `known_at` (QM/EOD fundamentals, TE macro, CIRO shorts), the pipeline stamps explicit conservative statutory/publication lags and tags `known_at_source` so strategies cannot unknowingly trade estimated timestamps at intraday precision.
|
|
||||||
- Principle 2: Clarify that **Rust owns all accounting, execution, and portfolio ledger semantics**, `libs/calculations` owns canonical performance/statistical formulas, and **batch feature jobs** own signal/feature values consumed identically by Python, the Tier 1 screener, and Tier 2 Rust strategies.
|
|
||||||
- **§2 (Where the project stands, lines 60, 75, 85, 96–106):**
|
|
||||||
- Line 60: Update October backlog count to **113 done / 5 deferred / 4 merged out of 122 tasks** (`docs/development/backlog/README.md`).
|
|
||||||
- Line 75: Note hardcoded Webshare proxy credential in `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` and Alpha Vantage key in `docs/data-sources.md:15` to be purged in Phase 0.
|
|
||||||
- Line 85: Fix `lint:check` split to `59 errors + 2 warnings = 61` in `phase1-inventory.ts` and **`4` errors** in WIP files (`env-safety.ts`, `builder.ts`, `mongodb/src/client.ts`).
|
|
||||||
- Lines 98–103: Add 31st collection **`qmFinancials-old` (`908k`)**, note existing **`CAD.FOREX` (`12.1k` 1d, `5.2M` 1m)** and **`teMarketData.USDCAD` (`2.9k` 1d)** FX series, and note `ibSymbols.exchangeId` represents execution/ATS venues rather than primary listing exchanges.
|
|
||||||
- **§3 (Decisions log, lines 123, 131):**
|
|
||||||
- **D1:** Amend to **hybrid curated store behind `MarketDataStore`**: DuckDB + Parquet for daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features; QuestDB `10.2.0` for `1m`/`5m`/`1h` intraday and hot streaming bars; remove the dual-backend parity harness.
|
|
||||||
- **D9:** Change status from `Proposed` to **Confirmed**, subject to separate-origin isolation, static HTML default in Agent Feed, `_`-local variable memory rules, and `marimo check` gating.
|
|
||||||
- **§5 (Data architecture and storage, lines 188–253):**
|
|
||||||
- Line 211: Remove the raw-SQL escape hatch for agents (restrict to human localhost sessions over pre-vault read-only views).
|
|
||||||
- Line 214 (`MarketDataStore`): Enforce server-side `VAULT_CUTOFF_DATE` ceiling on all research/SDK/MCP calls.
|
|
||||||
- Line 226: Specify `listing_id` is `INT32` in `MarketDataStore`/Parquet and `SYMBOL CAPACITY 65536 NOCACHE` inside QuestDB.
|
|
||||||
- Line 239: Delete the dual-backend parity harness; replace lines 232–237 with the four quantified workloads in §3 Q4 above.
|
|
||||||
- Line 245: Add mandatory split un-adjustment of `eodPrices.volume` and `eodIntraday1M` OHLCV during curation, and keep `bars_*` single-version with a separate `bar_revisions` table.
|
|
||||||
- Line 248: Replace EAV-only `fundamentals` with bitemporal `(listing_id, period_end, known_at)` deduplication + wide forward-filled PIT + TTM snapshots.
|
|
||||||
- Line 251: Replace *"known_at = release date"* on `macro` with *"lagged publication cutoff (`known_at_source = 'statutory_lag_estimate'`); final-revised values, restricted to regime filters."*
|
|
||||||
- **§6 (Step 1 — Security master, lines 264–351):**
|
|
||||||
- Add `instrument_identifier_history(instrument_id, id_type, id_value, valid_from, valid_to)` and `corporate_action_continuity` (linking primary delistings to same-ISIN OTC continuations such as `SIVB` → `SIVBQ`).
|
|
||||||
- Pass 1 & Pass 3 (lines 285, 300–310): Remove `MIC` blocking on `ibSymbols`; resolve `instrument` globally by Luhn-valid ISIN / CUSIP→ISIN, assign primary `listing.mic` from EOD `Exchange` + QM `exchange` (excluding `NMFQS` mutual funds from equities), and attach IB `conid` at `(instrument_id, currency)`. Require overlapping `[first_bar_date, last_bar_date]` spans on Tier 3/4 ticker matches.
|
|
||||||
- Pass 4 (lines 314–323): Specify cross-sectional 25-date batch extraction (`{ date: { $in: sampleDates } }` or DuckDB post-extract) instead of per-pair MongoDB queries.
|
|
||||||
- Pass 6 (line 341): Replace `eodSymbolChange` (only 230 rows, 2024–2025 US) with observed provider bar/filing validity spans + corporate actions.
|
|
||||||
- **§7 (Step 2 — Processing remaining datasets, lines 359–372):**
|
|
||||||
- Update Fundamentals (`qmFinancials` joined to `qmFilings.timefiled` + NI 51-102/SEC lag fallback; quarantine `eodFundamentalsOLD` snapshots), Earnings (`reportDate 16:05 ET` fallback when `announceTime == 'N/A'`), Filings (metadata + timestamps only until Form 4/SEDI XML parser is added — remove *"insider transactions extracted where present"*), Shorts (`+4` business-day CIRO publication lag), Macro (lagged regime-only), Futures (explicitly out of scope), and FX (`CAD.FOREX` + `teMarketData.USDCAD` already present).
|
|
||||||
- **§8 & §9 (Feature library & Backtesting, lines 391–458):**
|
|
||||||
- §8: Specify features are materialized by versioned DuckDB/Polars batch jobs and passed into Tier 2 Rust `Replay` + `StrategyContext` via a new `features` map so Python, Tier 1, and Tier 2 read identical values without rewriting indicators in zero-import TS.
|
|
||||||
- §9 line 418: Remove *"Reopens deferred task P06"* (document Tier 1 as a net-new columnar screener; reopen `D04` and `P03` instead).
|
|
||||||
- §9 Tier 2: Add atomic timestamp-slice marking (`F06` fix), simultaneous sell-proceeds netting on `Target` rebalances, OTC/Shumway delisting liquidation, and Arrow/Parquet dataset loading (replacing Postgres `JSONB` dataset snapshots for multi-asset runs).
|
|
||||||
- §9 Validation & Trial ledger: Define relatedness clusters by `(universe_market, horizon_bucket)`, store return/IC vectors to compute effective $\hat{N}$ for DSR + synchronous matrices for PBO, add nonzero `purge`/`embargo` to Walk-Forward & CPCV, and split unattended Research Validation from the human-only one-shot **Vault Holdout**.
|
|
||||||
- **§11 & §12 (Playground & Agents, lines 507–597):**
|
|
||||||
- §11: Enforce marimo separate-origin / static HTML snapshot rules and `marimo check` pre-validation.
|
|
||||||
- §12: Reuse `~/repos/studio/catalog/quant/library/library.yml` read-only for methodology/literature cards; isolate campaign agents in no-DB-network containers; enforce cumulative trial/compute budgets in PostgreSQL triggers.
|
|
||||||
- **§13 (Execution: paper to live on IB, lines 600–615):**
|
|
||||||
- Add `paper.rs` checkpoint compaction (fixing $O(N)$ genesis receipt replay), `MatchingReset` NAPI support, `IB Gateway + IBC` 5s/quote bridge on `9900K`, `conid + currency + primaryExchange` contract pinning, `FXCONV` (not `IDEALPRO`) vs. IB Margin negative-cash borrow modeling, TSX/TSXV `100/500/1000` board-lot sizing, and split Drift Monitoring into **Execution Drift** vs. **Feed Basis Drift**.
|
|
||||||
- **§14, §16, §17 (App, Roadmap, Immediate next steps):**
|
|
||||||
- §14: Note `dashboard` is empty (`0` files), wire existing `/research/agents` into `Sidebar.tsx`, and unify the two `lightweight-charts` wrappers.
|
|
||||||
- §16 & §17: Adopt the 6-phase vertical-slice roadmap and expanded Phase 0 checklist in §4 above.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Resolved Owner Decisions (2026-11-26)
|
|
||||||
|
|
||||||
1. **IBKR Account Type & Currency Policy — RESOLVED:**
|
|
||||||
**IBKR Margin account** (`USD` + `CAD`), plus **spot FX tradable as an alpha asset class** if edge is found.
|
|
||||||
- *Design impact:* Rust `Ledger` models per-currency cash/margin balances (`BTreeMap<Currency, Posting>`) with daily IBKR benchmark+spread interest on negative currency balances, uses `exchange="FXCONV"` for cash-funding sweeps (no virtual position), and supports `IDEALPRO` / `CAD.FOREX` as first-class tradable FX instruments when a strategy explicitly takes FX exposure.
|
|
||||||
|
|
||||||
2. **Vault Holdout vs. Recent-Regime Decay — RESOLVED:**
|
|
||||||
**No switch in v1; use a short rolling `6-month` Vault (`today - 6m`, or final 6 months of ingested data until ingestion catches up to present) + a mandatory Post-2023 Recency Gate.**
|
|
||||||
- *Design impact:* Keeps 2023–2025 AI/higher-rate regime data *inside* Zone 1 so dead pre-LLM signals get filtered out during walk-forward, while still reserving ~126 unseen trading days to catch agent p-hacking before Paper. A `full_history` switch (`vault_touched = true`) can be added later only if needed.
|
|
||||||
|
|
||||||
3. **Storage Split (Amending D1) — RESOLVED:**
|
|
||||||
**Confirmed Parquet + DuckDB from Day 1** for daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features; **QuestDB `10.2.0`** reserved for `1m`/`5m`/`1h` intraday and hot live/paper bars; dual-backend parity harness **cut**.
|
|
||||||
|
|
||||||
4. **v1 Data Scope (`teData` & `qmFilings`) — RESOLVED:**
|
|
||||||
**Confirmed lean v1:** `teData` restricted to lagged regime filters and `qmFilings` used for exact `timefiled` timestamps + form-type event counts; ALFRED macro vintages and Form 4 XML / SEDI insider transaction parsing deferred to Phase 2+.
|
|
||||||
|
|
||||||
5. **Live IB Intraday Symbol Cap — RESOLVED:**
|
|
||||||
**Confirmed $\le 50\text{–}80$ active streaming symbols** at a time (within IBKR's standard 100 market-data line limit, no paid quote boosters required initially).
|
|
||||||
161
SETUP-COMPLETE.md
Normal file
161
SETUP-COMPLETE.md
Normal file
|
|
@ -0,0 +1,161 @@
|
||||||
|
# 🚀 Trading Bot Docker Infrastructure Setup Complete!
|
||||||
|
|
||||||
|
Your Docker infrastructure has been successfully configured. Here's what you have:
|
||||||
|
|
||||||
|
## 📦 What's Included
|
||||||
|
|
||||||
|
### Core Services
|
||||||
|
- **🐉 Dragonfly**: Redis-compatible cache and event streaming (Port 6379)
|
||||||
|
- **🐘 PostgreSQL**: Operational database with complete trading schema (Port 5432)
|
||||||
|
- **📊 QuestDB**: Time-series database for market data (Ports 9000, 8812, 9009)
|
||||||
|
- **🍃 MongoDB**: Document storage for sentiment analysis and raw documents (Port 27017)
|
||||||
|
|
||||||
|
### Admin Tools
|
||||||
|
- **🔧 Redis Insight**: Dragonfly management GUI (Port 8001)
|
||||||
|
- **🛠️ PgAdmin**: PostgreSQL administration (Port 8080)
|
||||||
|
- **🍃 Mongo Express**: MongoDB document browser (Port 8081)
|
||||||
|
|
||||||
|
### Monitoring (Optional)
|
||||||
|
- **📈 Prometheus**: Metrics collection (Port 9090)
|
||||||
|
- **📊 Grafana**: Dashboards and alerting (Port 3000)
|
||||||
|
|
||||||
|
## 🏁 Getting Started
|
||||||
|
|
||||||
|
### Step 1: Start Docker Desktop
|
||||||
|
Make sure Docker Desktop is running on your Windows machine.
|
||||||
|
|
||||||
|
### Step 2: Start Infrastructure
|
||||||
|
```powershell
|
||||||
|
# Quick start - core services only
|
||||||
|
npm run infra:up
|
||||||
|
|
||||||
|
# Or with management script
|
||||||
|
npm run docker:start
|
||||||
|
|
||||||
|
# Full development environment
|
||||||
|
npm run dev:full
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 3: Access Admin Interfaces
|
||||||
|
```powershell
|
||||||
|
# Start admin tools
|
||||||
|
npm run docker:admin
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔗 Access URLs
|
||||||
|
|
||||||
|
Once running, access these services:
|
||||||
|
|
||||||
|
| Service | URL | Login |
|
||||||
|
|---------|-----|-------|
|
||||||
|
| **QuestDB Console** | http://localhost:9000 | No login required |
|
||||||
|
| **Redis Insight** | http://localhost:8001 | No login required |
|
||||||
|
| **Bull Board** | http://localhost:3001 | No login required |
|
||||||
|
| **PgAdmin** | http://localhost:8080 | `admin@tradingbot.local` / `admin123` |
|
||||||
|
| **Mongo Express** | http://localhost:8081 | `admin` / `admin123` |
|
||||||
|
| **Prometheus** | http://localhost:9090 | No login required |
|
||||||
|
| **Grafana** | http://localhost:3000 | `admin` / `admin123` |
|
||||||
|
| **Bull Board** | http://localhost:3001 | No login required |
|
||||||
|
|
||||||
|
## 📊 Database Connections
|
||||||
|
|
||||||
|
### From Your Trading Services
|
||||||
|
Update your `.env` file:
|
||||||
|
```env
|
||||||
|
# Dragonfly (Redis replacement)
|
||||||
|
DRAGONFLY_HOST=localhost
|
||||||
|
DRAGONFLY_PORT=6379
|
||||||
|
|
||||||
|
# PostgreSQL
|
||||||
|
POSTGRES_HOST=localhost
|
||||||
|
POSTGRES_PORT=5432
|
||||||
|
POSTGRES_DB=trading_bot
|
||||||
|
POSTGRES_USER=trading_user
|
||||||
|
POSTGRES_PASSWORD=trading_pass_dev
|
||||||
|
|
||||||
|
# QuestDB
|
||||||
|
QUESTDB_HOST=localhost
|
||||||
|
QUESTDB_PORT=8812
|
||||||
|
QUESTDB_DB=qdb
|
||||||
|
|
||||||
|
# MongoDB
|
||||||
|
MONGODB_HOST=localhost
|
||||||
|
MONGODB_PORT=27017
|
||||||
|
MONGODB_DB=trading_documents
|
||||||
|
MONGODB_USER=trading_admin
|
||||||
|
MONGODB_PASSWORD=trading_mongo_dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database Schema
|
||||||
|
PostgreSQL includes these pre-configured schemas:
|
||||||
|
- `trading.*` - Orders, positions, executions, accounts
|
||||||
|
- `strategy.*` - Strategies, signals, performance metrics
|
||||||
|
- `risk.*` - Risk limits, events, monitoring
|
||||||
|
- `audit.*` - System events, health checks, configuration
|
||||||
|
|
||||||
|
## 🛠️ Management Commands
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# Basic operations
|
||||||
|
npm run docker:start # Start core services
|
||||||
|
npm run docker:stop # Stop all services
|
||||||
|
npm run docker:status # Check service status
|
||||||
|
npm run docker:logs # View all logs
|
||||||
|
npm run docker:reset # Reset all data (destructive!)
|
||||||
|
|
||||||
|
# Additional services
|
||||||
|
npm run docker:admin # Start admin interfaces
|
||||||
|
npm run docker:monitoring # Start Prometheus & Grafana
|
||||||
|
|
||||||
|
# Development workflows
|
||||||
|
npm run dev:full # Infrastructure + admin + your services
|
||||||
|
npm run dev:clean # Reset + restart everything
|
||||||
|
|
||||||
|
# Direct PowerShell script access
|
||||||
|
./scripts/docker.ps1 start
|
||||||
|
./scripts/docker.ps1 logs -Service dragonfly
|
||||||
|
./scripts/docker.ps1 help
|
||||||
|
```
|
||||||
|
|
||||||
|
## ✅ Next Steps
|
||||||
|
|
||||||
|
1. **Start Docker Desktop** if not already running
|
||||||
|
2. **Run**: `npm run docker:start` to start core infrastructure
|
||||||
|
3. **Run**: `npm run docker:admin` to start admin tools
|
||||||
|
4. **Update** your environment variables to use the Docker services
|
||||||
|
5. **Test** Dragonfly connection in your EventPublisher service
|
||||||
|
6. **Verify** database schema in PgAdmin
|
||||||
|
7. **Start** your trading services with the new infrastructure
|
||||||
|
|
||||||
|
## 🎯 Ready for Integration
|
||||||
|
|
||||||
|
Your EventPublisher service is already configured to use Dragonfly. The infrastructure supports:
|
||||||
|
|
||||||
|
- ✅ **Event Streaming**: Dragonfly handles Redis Streams for real-time events
|
||||||
|
- ✅ **Caching**: High-performance caching with better memory efficiency
|
||||||
|
- ✅ **Operational Data**: PostgreSQL with complete trading schemas
|
||||||
|
- ✅ **Time-Series Data**: QuestDB for market data and analytics
|
||||||
|
- ✅ **Monitoring**: Full observability stack ready
|
||||||
|
- ✅ **Admin Tools**: Web-based management interfaces
|
||||||
|
|
||||||
|
The system is designed to scale from development to production with the same Docker configuration.
|
||||||
|
|
||||||
|
## 🔧 Troubleshooting
|
||||||
|
|
||||||
|
If you encounter issues:
|
||||||
|
```powershell
|
||||||
|
# Check Docker status
|
||||||
|
docker --version
|
||||||
|
docker-compose --version
|
||||||
|
|
||||||
|
# Verify services
|
||||||
|
npm run docker:status
|
||||||
|
|
||||||
|
# View specific service logs
|
||||||
|
./scripts/docker.ps1 logs -Service dragonfly
|
||||||
|
|
||||||
|
# Reset if needed
|
||||||
|
npm run docker:reset
|
||||||
|
```
|
||||||
|
|
||||||
|
**Happy Trading! 🚀📈**
|
||||||
825
SIMPLIFIED-ARCHITECTURE.md
Normal file
825
SIMPLIFIED-ARCHITECTURE.md
Normal file
|
|
@ -0,0 +1,825 @@
|
||||||
|
# Stock Bot - System Architecture
|
||||||
|
|
||||||
|
> **Updated**: June 2025
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
TypeScript microservices architecture for automated stock trading with real-time data processing and multi-database storage.
|
||||||
|
|
||||||
|
## Core Services
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||||
|
│ Data Service │ │Processing Service│ │Strategy Service │
|
||||||
|
│ • Market Data │────▶│ • Indicators │────▶│ • Strategies │
|
||||||
|
│ • Providers │ │ • Analytics │ │ • Backtesting │
|
||||||
|
│ • QuestDB │ │ • Validation │ │ • Signal Gen │
|
||||||
|
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||||
|
│ │ │
|
||||||
|
│ ┌─────────────────┐ │
|
||||||
|
└──────────────▶│ Event Bus │◀─────────────┘
|
||||||
|
│ (Dragonfly) │
|
||||||
|
└─────────────────┘
|
||||||
|
│
|
||||||
|
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||||
|
│Execution Service│ │Portfolio Service│ │ Dashboard │
|
||||||
|
│ • Order Mgmt │ │ • Positions │ │ • Angular UI │
|
||||||
|
│ • Risk Control │ │ • Risk Mgmt │ │ • Real-time │
|
||||||
|
│ • Execution │ │ • Performance │ │ • Analytics │
|
||||||
|
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## Services Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
stock-bot/
|
||||||
|
├── apps/
|
||||||
|
│ ├── data-service/ # Market data ingestion & storage
|
||||||
|
│ ├── execution-service/ # Order execution & broker integration
|
||||||
|
│ ├── portfolio-service/ # Position & risk management
|
||||||
|
│ ├── processing-service/ # Data processing & indicators
|
||||||
|
│ ├── strategy-service/ # Trading strategies & backtesting
|
||||||
|
│ └── dashboard/ # Angular UI (port 4200)
|
||||||
|
│
|
||||||
|
├── libs/ # Shared libraries
|
||||||
|
│ ├── logger/ # Centralized logging w/ Loki
|
||||||
|
│ ├── config/ # Configuration management
|
||||||
|
│ ├── event-bus/ # Event system
|
||||||
|
│ ├── mongodb-client/ # MongoDB operations
|
||||||
|
│ ├── postgres-client/ # PostgreSQL operations
|
||||||
|
│ ├── questdb-client/ # Time-series data
|
||||||
|
│ ├── http/ # HTTP client w/ proxy support
|
||||||
|
│ ├── cache/ # Caching layer
|
||||||
|
│ └── utils/ # Common utilities
|
||||||
|
│
|
||||||
|
└── database/ # Database configurations
|
||||||
|
├── mongodb/init/
|
||||||
|
└── postgres/init/
|
||||||
|
```
|
||||||
|
|
||||||
|
## Technology Stack
|
||||||
|
|
||||||
|
| Component | Technology | Purpose |
|
||||||
|
|-----------|------------|---------|
|
||||||
|
| **Runtime** | Bun | Fast JavaScript runtime |
|
||||||
|
| **Language** | TypeScript | Type-safe development |
|
||||||
|
| **Databases** | PostgreSQL, MongoDB, QuestDB | Multi-database architecture |
|
||||||
|
| **Caching** | Dragonfly (Redis) | Event bus & caching |
|
||||||
|
| **Frontend** | Angular 18 | Modern reactive UI |
|
||||||
|
| **Monitoring** | Prometheus, Grafana, Loki | Observability stack |
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install dependencies
|
||||||
|
bun install
|
||||||
|
|
||||||
|
# Start infrastructure
|
||||||
|
bun run infra:up
|
||||||
|
|
||||||
|
# Start services
|
||||||
|
bun run dev
|
||||||
|
|
||||||
|
# Access dashboard
|
||||||
|
# http://localhost:4200
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
- **Real-time Trading**: Live market data & order execution
|
||||||
|
- **Multi-Database**: PostgreSQL, MongoDB, QuestDB for different data types
|
||||||
|
- **Event-Driven**: Asynchronous communication via Dragonfly
|
||||||
|
- **Monitoring**: Full observability with metrics, logs, and tracing
|
||||||
|
- **Modular**: Shared libraries for common functionality
|
||||||
|
- **Type-Safe**: Full TypeScript coverage
|
||||||
|
│ ├── processing-service/ # Combined processing & indicators
|
||||||
|
│ │ ├── src/
|
||||||
|
│ │ │ ├── indicators/ # Technical indicators (uses @stock-bot/utils)
|
||||||
|
│ │ │ ├── processors/ # Data processing pipeline
|
||||||
|
│ │ │ ├── vectorized/ # Vectorized calculations
|
||||||
|
│ │ │ ├── services/
|
||||||
|
│ │ │ └── index.ts
|
||||||
|
│ │ └── package.json
|
||||||
|
│ │
|
||||||
|
│ ├── strategy-service/ # Combined strategy & backtesting
|
||||||
|
│ │ ├── src/
|
||||||
|
│ │ │ ├── strategies/ # Strategy implementations
|
||||||
|
│ │ │ ├── backtesting/ # Multi-mode backtesting engine
|
||||||
|
│ │ │ │ ├── modes/ # Backtesting modes
|
||||||
|
│ │ │ │ │ ├── live-mode.ts # Live trading mode
|
||||||
|
│ │ │ │ │ ├── event-mode.ts # Event-driven backtest
|
||||||
|
│ │ │ │ │ └── vector-mode.ts # Vectorized backtest
|
||||||
|
│ │ │ │ ├── engines/ # Execution engines
|
||||||
|
│ │ │ │ │ ├── event-engine.ts # Event-based simulation
|
||||||
|
│ │ │ │ │ ├── vector-engine.ts # Vectorized calculations
|
||||||
|
│ │ │ │ │ └── hybrid-engine.ts # Combined validation
|
||||||
|
│ │ │ │ ├── simulator.ts # Market simulator
|
||||||
|
│ │ │ │ ├── runner.ts # Backtest orchestrator
|
||||||
|
│ │ │ │ └── metrics.ts # Performance analysis
|
||||||
|
│ │ │ ├── live/ # Live strategy execution
|
||||||
|
│ │ │ ├── framework/ # Strategy framework
|
||||||
|
│ │ │ │ ├── base-strategy.ts
|
||||||
|
│ │ │ │ ├── execution-mode.ts
|
||||||
|
│ │ │ │ └── mode-factory.ts
|
||||||
|
│ │ │ └── index.ts
|
||||||
|
│ │ └── package.json
|
||||||
|
│ │
|
||||||
|
│ ├── execution-service/ # Combined order execution & simulation
|
||||||
|
│ │ ├── src/
|
||||||
|
│ │ │ ├── brokers/ # Live broker adapters
|
||||||
|
│ │ │ ├── simulation/ # Simulated execution
|
||||||
|
│ │ │ ├── unified/ # Unified execution interface
|
||||||
|
│ │ │ │ ├── executor.ts # Abstract executor
|
||||||
|
│ │ │ │ ├── live-executor.ts
|
||||||
|
│ │ │ │ ├── sim-executor.ts
|
||||||
|
│ │ │ │ └── vector-executor.ts
|
||||||
|
│ │ │ └── index.ts
|
||||||
|
│ │ └── package.json
|
||||||
|
│ │
|
||||||
|
│ ├── portfolio-service/ # Combined portfolio & risk management
|
||||||
|
│ │ ├── src/
|
||||||
|
│ │ │ ├── portfolio/ # Portfolio tracking
|
||||||
|
│ │ │ ├── risk/ # Risk management (uses @stock-bot/utils)
|
||||||
|
│ │ │ ├── positions/ # Position management
|
||||||
|
│ │ │ ├── performance/ # Performance tracking
|
||||||
|
│ │ │ └── index.ts
|
||||||
|
│ │ └── package.json
|
||||||
|
│ │
|
||||||
|
│ └── dashboard/ # Combined API & reporting
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── api/ # REST API
|
||||||
|
│ │ ├── web/ # Web interface (Angular)
|
||||||
|
│ │ ├── reports/ # Report generation
|
||||||
|
│ │ ├── websockets/ # Real-time updates
|
||||||
|
│ │ └── index.ts
|
||||||
|
│ └── package.json
|
||||||
|
│
|
||||||
|
├── libs/ # ✅ Your existing shared libraries
|
||||||
|
│ ├── config/ # ✅ Environment configuration
|
||||||
|
│ ├── http/ # ✅ HTTP utilities
|
||||||
|
│ ├── logger/ # ✅ Loki-integrated logging
|
||||||
|
│ ├── mongodb-client/ # ✅ MongoDB operations
|
||||||
|
│ ├── postgres-client/ # ✅ PostgreSQL operations
|
||||||
|
│ ├── questdb-client/ # ✅ Time-series data
|
||||||
|
│ ├── types/ # ✅ Shared TypeScript types
|
||||||
|
│ ├── utils/ # ✅ Calculations & utilities
|
||||||
|
│ ├── event-bus/ # 🆕 Dragonfly event system
|
||||||
|
│ ├── strategy-engine/ # 🆕 Strategy framework
|
||||||
|
│ ├── vector-engine/ # 🆕 Vectorized calculations
|
||||||
|
│ └── data-frame/ # 🆕 DataFrame operations
|
||||||
|
```
|
||||||
|
|
||||||
|
## Multi-Mode Backtesting Architecture
|
||||||
|
|
||||||
|
### 1. Execution Mode Framework
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export abstract class ExecutionMode {
|
||||||
|
protected logger = createLogger(this.constructor.name);
|
||||||
|
protected config = new ServiceConfig();
|
||||||
|
|
||||||
|
abstract name: string;
|
||||||
|
abstract executeOrder(order: Order): Promise<OrderResult>;
|
||||||
|
abstract getCurrentTime(): Date;
|
||||||
|
abstract getMarketData(symbol: string): Promise<MarketData>;
|
||||||
|
abstract publishEvent(event: string, data: any): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum BacktestMode {
|
||||||
|
LIVE = 'live',
|
||||||
|
EVENT_DRIVEN = 'event-driven',
|
||||||
|
VECTORIZED = 'vectorized',
|
||||||
|
HYBRID = 'hybrid'
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Live Trading Mode
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class LiveMode extends ExecutionMode {
|
||||||
|
name = 'live';
|
||||||
|
private broker = new BrokerClient(this.config.getBrokerConfig());
|
||||||
|
private eventBus = new EventBus();
|
||||||
|
|
||||||
|
async executeOrder(order: Order): Promise<OrderResult> {
|
||||||
|
this.logger.info('Executing live order', { orderId: order.id });
|
||||||
|
|
||||||
|
// Execute via real broker
|
||||||
|
const result = await this.broker.placeOrder(order);
|
||||||
|
|
||||||
|
// Publish to event bus
|
||||||
|
await this.eventBus.publish('order.executed', result);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
getCurrentTime(): Date {
|
||||||
|
return new Date(); // Real time
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMarketData(symbol: string): Promise<MarketData> {
|
||||||
|
// Get live market data
|
||||||
|
return await this.marketDataService.getLiveData(symbol);
|
||||||
|
}
|
||||||
|
|
||||||
|
async publishEvent(event: string, data: any): Promise<void> {
|
||||||
|
await this.eventBus.publish(event, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Event-Driven Backtesting Mode
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class EventBacktestMode extends ExecutionMode {
|
||||||
|
name = 'event-driven';
|
||||||
|
private simulator = new MarketSimulator();
|
||||||
|
private eventBus = new InMemoryEventBus(); // In-memory for simulation
|
||||||
|
private simulationTime: Date;
|
||||||
|
private historicalData: Map<string, MarketData[]>;
|
||||||
|
|
||||||
|
constructor(private config: BacktestConfig) {
|
||||||
|
super();
|
||||||
|
this.simulationTime = config.startDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
async executeOrder(order: Order): Promise<OrderResult> {
|
||||||
|
this.logger.debug('Simulating order execution', {
|
||||||
|
orderId: order.id,
|
||||||
|
simulationTime: this.simulationTime
|
||||||
|
});
|
||||||
|
|
||||||
|
// Realistic order simulation with slippage, fees
|
||||||
|
const result = await this.simulator.executeOrder(order, {
|
||||||
|
currentTime: this.simulationTime,
|
||||||
|
marketData: await this.getMarketData(order.symbol),
|
||||||
|
slippageModel: this.config.slippageModel,
|
||||||
|
commissionModel: this.config.commissionModel
|
||||||
|
});
|
||||||
|
|
||||||
|
// Publish to simulation event bus
|
||||||
|
await this.eventBus.publish('order.executed', result);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
getCurrentTime(): Date {
|
||||||
|
return this.simulationTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMarketData(symbol: string): Promise<MarketData> {
|
||||||
|
const data = this.historicalData.get(symbol) || [];
|
||||||
|
return data.find(d => d.timestamp <= this.simulationTime) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async publishEvent(event: string, data: any): Promise<void> {
|
||||||
|
await this.eventBus.publish(event, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Progress simulation time
|
||||||
|
advanceTime(newTime: Date): void {
|
||||||
|
this.simulationTime = newTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Vectorized Backtesting Mode
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class VectorBacktestMode extends ExecutionMode {
|
||||||
|
name = 'vectorized';
|
||||||
|
private dataFrame: DataFrame;
|
||||||
|
private currentIndex: number = 0;
|
||||||
|
|
||||||
|
constructor(private config: VectorBacktestConfig) {
|
||||||
|
super();
|
||||||
|
this.dataFrame = new DataFrame(config.historicalData);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vectorized execution - processes entire dataset at once
|
||||||
|
async executeVectorizedBacktest(strategy: VectorizedStrategy): Promise<BacktestResult> {
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
this.logger.info('Starting vectorized backtest', {
|
||||||
|
strategy: strategy.name,
|
||||||
|
dataPoints: this.dataFrame.length
|
||||||
|
});
|
||||||
|
|
||||||
|
// Generate all signals at once using your utils library
|
||||||
|
const signals = this.generateVectorizedSignals(strategy);
|
||||||
|
|
||||||
|
// Calculate performance metrics vectorized
|
||||||
|
const performance = this.calculateVectorizedPerformance(signals);
|
||||||
|
|
||||||
|
// Apply trading costs if specified
|
||||||
|
if (this.config.tradingCosts) {
|
||||||
|
this.applyTradingCosts(performance, signals);
|
||||||
|
}
|
||||||
|
|
||||||
|
const executionTime = Date.now() - startTime;
|
||||||
|
|
||||||
|
this.logger.info('Vectorized backtest completed', {
|
||||||
|
executionTime,
|
||||||
|
totalReturn: performance.totalReturn,
|
||||||
|
sharpeRatio: performance.sharpeRatio
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
mode: 'vectorized',
|
||||||
|
strategy: strategy.name,
|
||||||
|
performance,
|
||||||
|
executionTime,
|
||||||
|
signals
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateVectorizedSignals(strategy: VectorizedStrategy): DataFrame {
|
||||||
|
const prices = this.dataFrame.get('close');
|
||||||
|
|
||||||
|
// Use your existing technical indicators from @stock-bot/utils
|
||||||
|
const indicators = {
|
||||||
|
sma20: sma(prices, 20),
|
||||||
|
sma50: sma(prices, 50),
|
||||||
|
rsi: rsi(prices, 14),
|
||||||
|
macd: macd(prices)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Generate position signals vectorized
|
||||||
|
const positions = strategy.generatePositions(this.dataFrame, indicators);
|
||||||
|
|
||||||
|
return new DataFrame({
|
||||||
|
...this.dataFrame.toObject(),
|
||||||
|
...indicators,
|
||||||
|
positions
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private calculateVectorizedPerformance(signals: DataFrame): PerformanceMetrics {
|
||||||
|
const prices = signals.get('close');
|
||||||
|
const positions = signals.get('positions');
|
||||||
|
|
||||||
|
// Calculate returns vectorized
|
||||||
|
const returns = prices.slice(1).map((price, i) =>
|
||||||
|
(price - prices[i]) / prices[i]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Strategy returns = position[t-1] * market_return[t]
|
||||||
|
const strategyReturns = returns.map((ret, i) =>
|
||||||
|
(positions[i] || 0) * ret
|
||||||
|
);
|
||||||
|
|
||||||
|
// Use your existing performance calculation utilities
|
||||||
|
return {
|
||||||
|
totalReturn: calculateTotalReturn(strategyReturns),
|
||||||
|
sharpeRatio: calculateSharpeRatio(strategyReturns),
|
||||||
|
maxDrawdown: calculateMaxDrawdown(strategyReturns),
|
||||||
|
volatility: calculateVolatility(strategyReturns),
|
||||||
|
winRate: calculateWinRate(strategyReturns)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard interface methods (not used in vectorized mode)
|
||||||
|
async executeOrder(order: Order): Promise<OrderResult> {
|
||||||
|
throw new Error('Use executeVectorizedBacktest for vectorized mode');
|
||||||
|
}
|
||||||
|
|
||||||
|
getCurrentTime(): Date {
|
||||||
|
return this.dataFrame.getTimestamp(this.currentIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMarketData(symbol: string): Promise<MarketData> {
|
||||||
|
return this.dataFrame.getRow(this.currentIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
async publishEvent(event: string, data: any): Promise<void> {
|
||||||
|
// No-op for vectorized mode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Hybrid Validation Mode
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class HybridBacktestMode extends ExecutionMode {
|
||||||
|
name = 'hybrid';
|
||||||
|
private eventMode: EventBacktestMode;
|
||||||
|
private vectorMode: VectorBacktestMode;
|
||||||
|
|
||||||
|
constructor(config: BacktestConfig) {
|
||||||
|
super();
|
||||||
|
this.eventMode = new EventBacktestMode(config);
|
||||||
|
this.vectorMode = new VectorBacktestMode(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
async validateStrategy(
|
||||||
|
strategy: BaseStrategy,
|
||||||
|
tolerance: number = 0.001
|
||||||
|
): Promise<ValidationResult> {
|
||||||
|
|
||||||
|
this.logger.info('Starting hybrid validation', {
|
||||||
|
strategy: strategy.name,
|
||||||
|
tolerance
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run vectorized backtest (fast)
|
||||||
|
const vectorResult = await this.vectorMode.executeVectorizedBacktest(
|
||||||
|
strategy as VectorizedStrategy
|
||||||
|
);
|
||||||
|
|
||||||
|
// Run event-driven backtest (realistic)
|
||||||
|
const eventResult = await this.runEventBacktest(strategy);
|
||||||
|
|
||||||
|
// Compare results
|
||||||
|
const performanceDiff = Math.abs(
|
||||||
|
vectorResult.performance.totalReturn -
|
||||||
|
eventResult.performance.totalReturn
|
||||||
|
);
|
||||||
|
|
||||||
|
const isValid = performanceDiff < tolerance;
|
||||||
|
|
||||||
|
this.logger.info('Hybrid validation completed', {
|
||||||
|
isValid,
|
||||||
|
performanceDifference: performanceDiff,
|
||||||
|
recommendation: isValid ? 'vectorized' : 'event-driven'
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
isValid,
|
||||||
|
performanceDifference: performanceDiff,
|
||||||
|
vectorizedResult: vectorResult,
|
||||||
|
eventResult,
|
||||||
|
recommendation: isValid ?
|
||||||
|
'Vectorized results are reliable for this strategy' :
|
||||||
|
'Use event-driven backtesting for accurate results'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard interface methods delegate to event mode
|
||||||
|
async executeOrder(order: Order): Promise<OrderResult> {
|
||||||
|
return await this.eventMode.executeOrder(order);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCurrentTime(): Date {
|
||||||
|
return this.eventMode.getCurrentTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMarketData(symbol: string): Promise<MarketData> {
|
||||||
|
return await this.eventMode.getMarketData(symbol);
|
||||||
|
}
|
||||||
|
|
||||||
|
async publishEvent(event: string, data: any): Promise<void> {
|
||||||
|
await this.eventMode.publishEvent(event, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Unified Strategy Implementation
|
||||||
|
|
||||||
|
### Base Strategy Framework
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export abstract class BaseStrategy {
|
||||||
|
protected mode: ExecutionMode;
|
||||||
|
protected logger = createLogger(this.constructor.name);
|
||||||
|
|
||||||
|
abstract name: string;
|
||||||
|
abstract parameters: Record<string, any>;
|
||||||
|
|
||||||
|
constructor(mode: ExecutionMode) {
|
||||||
|
this.mode = mode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Works identically across all modes
|
||||||
|
abstract onPriceUpdate(data: PriceData): Promise<void>;
|
||||||
|
abstract onIndicatorUpdate(data: IndicatorData): Promise<void>;
|
||||||
|
|
||||||
|
protected async emitSignal(signal: TradeSignal): Promise<void> {
|
||||||
|
this.logger.debug('Emitting trade signal', { signal });
|
||||||
|
|
||||||
|
// Mode handles whether this is live, simulated, or vectorized
|
||||||
|
const order = this.createOrder(signal);
|
||||||
|
const result = await this.mode.executeOrder(order);
|
||||||
|
|
||||||
|
await this.mode.publishEvent('trade.executed', {
|
||||||
|
signal,
|
||||||
|
order,
|
||||||
|
result,
|
||||||
|
timestamp: this.mode.getCurrentTime()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private createOrder(signal: TradeSignal): Order {
|
||||||
|
return {
|
||||||
|
id: generateId(),
|
||||||
|
symbol: signal.symbol,
|
||||||
|
side: signal.action,
|
||||||
|
quantity: signal.quantity,
|
||||||
|
type: 'market',
|
||||||
|
timestamp: this.mode.getCurrentTime()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vectorized strategy interface
|
||||||
|
export interface VectorizedStrategy {
|
||||||
|
name: string;
|
||||||
|
parameters: Record<string, any>;
|
||||||
|
generatePositions(data: DataFrame, indicators: any): number[];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example Strategy Implementation
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class SMAStrategy extends BaseStrategy implements VectorizedStrategy {
|
||||||
|
name = 'SMA-Crossover';
|
||||||
|
parameters = { fastPeriod: 10, slowPeriod: 20 };
|
||||||
|
|
||||||
|
private fastSMA: number[] = [];
|
||||||
|
private slowSMA: number[] = [];
|
||||||
|
|
||||||
|
async onPriceUpdate(data: PriceData): Promise<void> {
|
||||||
|
// Same logic for live, event-driven, and hybrid modes
|
||||||
|
this.fastSMA.push(data.close);
|
||||||
|
this.slowSMA.push(data.close);
|
||||||
|
|
||||||
|
if (this.fastSMA.length > this.parameters.fastPeriod) {
|
||||||
|
this.fastSMA.shift();
|
||||||
|
}
|
||||||
|
if (this.slowSMA.length > this.parameters.slowPeriod) {
|
||||||
|
this.slowSMA.shift();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.fastSMA.length === this.parameters.fastPeriod &&
|
||||||
|
this.slowSMA.length === this.parameters.slowPeriod) {
|
||||||
|
|
||||||
|
const fastAvg = sma(this.fastSMA, this.parameters.fastPeriod)[0];
|
||||||
|
const slowAvg = sma(this.slowSMA, this.parameters.slowPeriod)[0];
|
||||||
|
|
||||||
|
if (fastAvg > slowAvg) {
|
||||||
|
await this.emitSignal({
|
||||||
|
symbol: data.symbol,
|
||||||
|
action: 'BUY',
|
||||||
|
quantity: 100,
|
||||||
|
confidence: 0.8
|
||||||
|
});
|
||||||
|
} else if (fastAvg < slowAvg) {
|
||||||
|
await this.emitSignal({
|
||||||
|
symbol: data.symbol,
|
||||||
|
action: 'SELL',
|
||||||
|
quantity: 100,
|
||||||
|
confidence: 0.8
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async onIndicatorUpdate(data: IndicatorData): Promise<void> {
|
||||||
|
// Handle pre-calculated indicators
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vectorized implementation for fast backtesting
|
||||||
|
generatePositions(data: DataFrame, indicators: any): number[] {
|
||||||
|
const { sma20: fastSMA, sma50: slowSMA } = indicators;
|
||||||
|
|
||||||
|
return fastSMA.map((fast, i) => {
|
||||||
|
const slow = slowSMA[i];
|
||||||
|
if (isNaN(fast) || isNaN(slow)) return 0;
|
||||||
|
|
||||||
|
// Long when fast > slow, short when fast < slow
|
||||||
|
return fast > slow ? 1 : (fast < slow ? -1 : 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Mode Factory and Service Integration
|
||||||
|
|
||||||
|
### Mode Factory
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class ModeFactory {
|
||||||
|
static create(mode: BacktestMode, config: any): ExecutionMode {
|
||||||
|
switch (mode) {
|
||||||
|
case BacktestMode.LIVE:
|
||||||
|
return new LiveMode();
|
||||||
|
case BacktestMode.EVENT_DRIVEN:
|
||||||
|
return new EventBacktestMode(config);
|
||||||
|
case BacktestMode.VECTORIZED:
|
||||||
|
return new VectorBacktestMode(config);
|
||||||
|
case BacktestMode.HYBRID:
|
||||||
|
return new HybridBacktestMode(config);
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown mode: ${mode}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Strategy Service Integration
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class StrategyService {
|
||||||
|
private logger = createLogger('strategy-service');
|
||||||
|
|
||||||
|
async runStrategy(
|
||||||
|
strategyName: string,
|
||||||
|
mode: BacktestMode,
|
||||||
|
config: any
|
||||||
|
): Promise<any> {
|
||||||
|
|
||||||
|
const executionMode = ModeFactory.create(mode, config);
|
||||||
|
const strategy = await this.loadStrategy(strategyName, executionMode);
|
||||||
|
|
||||||
|
this.logger.info('Starting strategy execution', {
|
||||||
|
strategy: strategyName,
|
||||||
|
mode,
|
||||||
|
config
|
||||||
|
});
|
||||||
|
|
||||||
|
switch (mode) {
|
||||||
|
case BacktestMode.LIVE:
|
||||||
|
return await this.runLiveStrategy(strategy);
|
||||||
|
|
||||||
|
case BacktestMode.EVENT_DRIVEN:
|
||||||
|
return await this.runEventBacktest(strategy, config);
|
||||||
|
|
||||||
|
case BacktestMode.VECTORIZED:
|
||||||
|
return await (executionMode as VectorBacktestMode)
|
||||||
|
.executeVectorizedBacktest(strategy as VectorizedStrategy);
|
||||||
|
|
||||||
|
case BacktestMode.HYBRID:
|
||||||
|
return await (executionMode as HybridBacktestMode)
|
||||||
|
.validateStrategy(strategy, config.tolerance);
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new Error(`Unsupported mode: ${mode}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async optimizeStrategy(
|
||||||
|
strategyName: string,
|
||||||
|
parameterGrid: Record<string, any[]>,
|
||||||
|
config: BacktestConfig
|
||||||
|
): Promise<OptimizationResult[]> {
|
||||||
|
|
||||||
|
const results: OptimizationResult[] = [];
|
||||||
|
const combinations = this.generateParameterCombinations(parameterGrid);
|
||||||
|
|
||||||
|
this.logger.info('Starting parameter optimization', {
|
||||||
|
strategy: strategyName,
|
||||||
|
combinations: combinations.length
|
||||||
|
});
|
||||||
|
|
||||||
|
// Use vectorized mode for fast parameter optimization
|
||||||
|
const vectorMode = new VectorBacktestMode(config);
|
||||||
|
|
||||||
|
// Can be parallelized
|
||||||
|
await Promise.all(
|
||||||
|
combinations.map(async (params) => {
|
||||||
|
const strategy = await this.loadStrategy(strategyName, vectorMode, params);
|
||||||
|
const result = await vectorMode.executeVectorizedBacktest(
|
||||||
|
strategy as VectorizedStrategy
|
||||||
|
);
|
||||||
|
|
||||||
|
results.push({
|
||||||
|
parameters: params,
|
||||||
|
performance: result.performance,
|
||||||
|
executionTime: result.executionTime
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// Sort by Sharpe ratio
|
||||||
|
return results.sort((a, b) =>
|
||||||
|
b.performance.sharpeRatio - a.performance.sharpeRatio
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Service Configuration
|
||||||
|
|
||||||
|
### Environment-Based Mode Selection
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class ServiceConfig {
|
||||||
|
getTradingConfig(): TradingConfig {
|
||||||
|
return {
|
||||||
|
mode: (process.env.TRADING_MODE as BacktestMode) || BacktestMode.LIVE,
|
||||||
|
brokerConfig: {
|
||||||
|
apiKey: process.env.BROKER_API_KEY,
|
||||||
|
sandbox: process.env.BROKER_SANDBOX === 'true'
|
||||||
|
},
|
||||||
|
backtestConfig: {
|
||||||
|
startDate: new Date(process.env.BACKTEST_START_DATE || '2023-01-01'),
|
||||||
|
endDate: new Date(process.env.BACKTEST_END_DATE || '2024-01-01'),
|
||||||
|
initialCapital: parseFloat(process.env.INITIAL_CAPITAL || '100000'),
|
||||||
|
slippageModel: process.env.SLIPPAGE_MODEL || 'linear',
|
||||||
|
commissionModel: process.env.COMMISSION_MODEL || 'fixed'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### CLI Interface
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// CLI for running different modes
|
||||||
|
import { Command } from 'commander';
|
||||||
|
|
||||||
|
const program = new Command();
|
||||||
|
|
||||||
|
program
|
||||||
|
.name('stock-bot')
|
||||||
|
.description('Stock Trading Bot with Multi-Mode Backtesting');
|
||||||
|
|
||||||
|
program
|
||||||
|
.command('live')
|
||||||
|
.description('Run live trading')
|
||||||
|
.option('-s, --strategy <strategy>', 'Strategy to run')
|
||||||
|
.action(async (options) => {
|
||||||
|
const strategyService = new StrategyService();
|
||||||
|
await strategyService.runStrategy(
|
||||||
|
options.strategy,
|
||||||
|
BacktestMode.LIVE,
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
program
|
||||||
|
.command('backtest')
|
||||||
|
.description('Run backtesting')
|
||||||
|
.option('-s, --strategy <strategy>', 'Strategy to test')
|
||||||
|
.option('-m, --mode <mode>', 'Backtest mode (event|vector|hybrid)', 'event')
|
||||||
|
.option('-f, --from <date>', 'Start date')
|
||||||
|
.option('-t, --to <date>', 'End date')
|
||||||
|
.action(async (options) => {
|
||||||
|
const strategyService = new StrategyService();
|
||||||
|
await strategyService.runStrategy(
|
||||||
|
options.strategy,
|
||||||
|
options.mode as BacktestMode,
|
||||||
|
{
|
||||||
|
startDate: new Date(options.from),
|
||||||
|
endDate: new Date(options.to)
|
||||||
|
}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
program
|
||||||
|
.command('optimize')
|
||||||
|
.description('Optimize strategy parameters')
|
||||||
|
.option('-s, --strategy <strategy>', 'Strategy to optimize')
|
||||||
|
.option('-p, --params <params>', 'Parameter grid JSON')
|
||||||
|
.action(async (options) => {
|
||||||
|
const strategyService = new StrategyService();
|
||||||
|
const paramGrid = JSON.parse(options.params);
|
||||||
|
await strategyService.optimizeStrategy(
|
||||||
|
options.strategy,
|
||||||
|
paramGrid,
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
program.parse();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Performance Comparison
|
||||||
|
|
||||||
|
### Execution Speed by Mode
|
||||||
|
|
||||||
|
| Mode | Data Points/Second | Memory Usage | Use Case |
|
||||||
|
|------|-------------------|--------------|----------|
|
||||||
|
| **Live** | Real-time | Low | Production trading |
|
||||||
|
| **Event-Driven** | ~1,000 | Medium | Realistic validation |
|
||||||
|
| **Vectorized** | ~100,000+ | High | Parameter optimization |
|
||||||
|
| **Hybrid** | Combined | Medium | Strategy validation |
|
||||||
|
|
||||||
|
### When to Use Each Mode
|
||||||
|
|
||||||
|
- **Live Mode**: Production trading with real money
|
||||||
|
- **Event-Driven**: Final strategy validation, complex order logic
|
||||||
|
- **Vectorized**: Initial development, parameter optimization, quick testing
|
||||||
|
- **Hybrid**: Validating vectorized results against realistic simulation
|
||||||
|
|
||||||
|
## Integration with Your Existing Libraries
|
||||||
|
|
||||||
|
This architecture leverages all your existing infrastructure:
|
||||||
|
|
||||||
|
- **@stock-bot/config**: Environment management
|
||||||
|
- **@stock-bot/logger**: Comprehensive logging with Loki
|
||||||
|
- **@stock-bot/utils**: All technical indicators and calculations
|
||||||
|
- **@stock-bot/questdb-client**: Time-series data storage
|
||||||
|
- **@stock-bot/postgres-client**: Transactional data
|
||||||
|
- **@stock-bot/mongodb-client**: Configuration storage
|
||||||
|
|
||||||
|
## Key Benefits
|
||||||
|
|
||||||
|
1. **Unified Codebase**: Same strategy logic across all modes
|
||||||
|
2. **Performance Flexibility**: Choose speed vs accuracy based on needs
|
||||||
|
3. **Validation Pipeline**: Hybrid mode ensures vectorized results are accurate
|
||||||
|
4. **Production Ready**: Live mode for actual trading
|
||||||
|
5. **Development Friendly**: Fast iteration with vectorized backtesting
|
||||||
|
|
||||||
|
This simplified architecture reduces complexity while providing comprehensive backtesting capabilities that scale from rapid prototyping to production trading.
|
||||||
17
apps/dashboard/.editorconfig
Normal file
17
apps/dashboard/.editorconfig
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
# Editor configuration, see https://editorconfig.org
|
||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 2
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
|
[*.ts]
|
||||||
|
quote_type = single
|
||||||
|
ij_typescript_use_double_quotes = false
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
max_line_length = off
|
||||||
|
trim_trailing_whitespace = false
|
||||||
42
apps/dashboard/.gitignore
vendored
Normal file
42
apps/dashboard/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
|
||||||
|
|
||||||
|
# Compiled output
|
||||||
|
/dist
|
||||||
|
/tmp
|
||||||
|
/out-tsc
|
||||||
|
/bazel-out
|
||||||
|
|
||||||
|
# Node
|
||||||
|
/node_modules
|
||||||
|
npm-debug.log
|
||||||
|
yarn-error.log
|
||||||
|
|
||||||
|
# IDEs and editors
|
||||||
|
.idea/
|
||||||
|
.project
|
||||||
|
.classpath
|
||||||
|
.c9/
|
||||||
|
*.launch
|
||||||
|
.settings/
|
||||||
|
*.sublime-workspace
|
||||||
|
|
||||||
|
# Visual Studio Code
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
|
!.vscode/tasks.json
|
||||||
|
!.vscode/launch.json
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.history/*
|
||||||
|
|
||||||
|
# Miscellaneous
|
||||||
|
/.angular/cache
|
||||||
|
.sass-cache/
|
||||||
|
/connect.lock
|
||||||
|
/coverage
|
||||||
|
/libpeerconnection.log
|
||||||
|
testem.log
|
||||||
|
/typings
|
||||||
|
|
||||||
|
# System files
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
5
apps/dashboard/.postcssrc.json
Normal file
5
apps/dashboard/.postcssrc.json
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
{
|
||||||
|
"plugins": {
|
||||||
|
"@tailwindcss/postcss": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
4
apps/dashboard/.vscode/extensions.json
vendored
Normal file
4
apps/dashboard/.vscode/extensions.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
|
||||||
|
"recommendations": ["angular.ng-template"]
|
||||||
|
}
|
||||||
20
apps/dashboard/.vscode/launch.json
vendored
Normal file
20
apps/dashboard/.vscode/launch.json
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
{
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "ng serve",
|
||||||
|
"type": "chrome",
|
||||||
|
"request": "launch",
|
||||||
|
"preLaunchTask": "npm: start",
|
||||||
|
"url": "http://localhost:4200/"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ng test",
|
||||||
|
"type": "chrome",
|
||||||
|
"request": "launch",
|
||||||
|
"preLaunchTask": "npm: test",
|
||||||
|
"url": "http://localhost:9876/debug.html"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
42
apps/dashboard/.vscode/tasks.json
vendored
Normal file
42
apps/dashboard/.vscode/tasks.json
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
{
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
|
||||||
|
"version": "2.0.0",
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"type": "npm",
|
||||||
|
"script": "start",
|
||||||
|
"isBackground": true,
|
||||||
|
"problemMatcher": {
|
||||||
|
"owner": "typescript",
|
||||||
|
"pattern": "$tsc",
|
||||||
|
"background": {
|
||||||
|
"activeOnStart": true,
|
||||||
|
"beginsPattern": {
|
||||||
|
"regexp": "(.*?)"
|
||||||
|
},
|
||||||
|
"endsPattern": {
|
||||||
|
"regexp": "bundle generation complete"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "npm",
|
||||||
|
"script": "test",
|
||||||
|
"isBackground": true,
|
||||||
|
"problemMatcher": {
|
||||||
|
"owner": "typescript",
|
||||||
|
"pattern": "$tsc",
|
||||||
|
"background": {
|
||||||
|
"activeOnStart": true,
|
||||||
|
"beginsPattern": {
|
||||||
|
"regexp": "(.*?)"
|
||||||
|
},
|
||||||
|
"endsPattern": {
|
||||||
|
"regexp": "bundle generation complete"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
59
apps/dashboard/README.md
Normal file
59
apps/dashboard/README.md
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
# TradingDashboard
|
||||||
|
|
||||||
|
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 20.0.0.
|
||||||
|
|
||||||
|
## Development server
|
||||||
|
|
||||||
|
To start a local development server, run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ng serve
|
||||||
|
```
|
||||||
|
|
||||||
|
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
|
||||||
|
|
||||||
|
## Code scaffolding
|
||||||
|
|
||||||
|
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ng generate component component-name
|
||||||
|
```
|
||||||
|
|
||||||
|
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ng generate --help
|
||||||
|
```
|
||||||
|
|
||||||
|
## Building
|
||||||
|
|
||||||
|
To build the project run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ng build
|
||||||
|
```
|
||||||
|
|
||||||
|
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
|
||||||
|
|
||||||
|
## Running unit tests
|
||||||
|
|
||||||
|
To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ng test
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running end-to-end tests
|
||||||
|
|
||||||
|
For end-to-end (e2e) testing, run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ng e2e
|
||||||
|
```
|
||||||
|
|
||||||
|
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
|
||||||
|
|
||||||
|
## Additional Resources
|
||||||
|
|
||||||
|
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
|
||||||
90
apps/dashboard/angular.json
Normal file
90
apps/dashboard/angular.json
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
{
|
||||||
|
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||||
|
"version": 1,
|
||||||
|
"cli": {
|
||||||
|
"packageManager": "npm"
|
||||||
|
},
|
||||||
|
"newProjectRoot": "projects",
|
||||||
|
"projects": {
|
||||||
|
"trading-dashboard": {
|
||||||
|
"projectType": "application",
|
||||||
|
"schematics": {
|
||||||
|
"@schematics/angular:component": {
|
||||||
|
"style": "css"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"prefix": "app",
|
||||||
|
"architect": {
|
||||||
|
"build": {
|
||||||
|
"builder": "@angular/build:application",
|
||||||
|
"options": {
|
||||||
|
"browser": "src/main.ts",
|
||||||
|
"tsConfig": "tsconfig.app.json",
|
||||||
|
"inlineStyleLanguage": "css",
|
||||||
|
"assets": [
|
||||||
|
{
|
||||||
|
"glob": "**/*",
|
||||||
|
"input": "public"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"styles": ["src/styles.css"]
|
||||||
|
},
|
||||||
|
"configurations": {
|
||||||
|
"production": {
|
||||||
|
"budgets": [
|
||||||
|
{
|
||||||
|
"type": "initial",
|
||||||
|
"maximumWarning": "500kB",
|
||||||
|
"maximumError": "1MB"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "anyComponentStyle",
|
||||||
|
"maximumWarning": "4kB",
|
||||||
|
"maximumError": "8kB"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outputHashing": "all"
|
||||||
|
},
|
||||||
|
"development": {
|
||||||
|
"optimization": false,
|
||||||
|
"extractLicenses": false,
|
||||||
|
"sourceMap": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"defaultConfiguration": "production"
|
||||||
|
},
|
||||||
|
"serve": {
|
||||||
|
"builder": "@angular/build:dev-server",
|
||||||
|
"configurations": {
|
||||||
|
"production": {
|
||||||
|
"buildTarget": "trading-dashboard:build:production"
|
||||||
|
},
|
||||||
|
"development": {
|
||||||
|
"buildTarget": "trading-dashboard:build:development"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"defaultConfiguration": "development"
|
||||||
|
},
|
||||||
|
"extract-i18n": {
|
||||||
|
"builder": "@angular/build:extract-i18n"
|
||||||
|
},
|
||||||
|
"test": {
|
||||||
|
"builder": "@angular/build:karma",
|
||||||
|
"options": {
|
||||||
|
"tsConfig": "tsconfig.spec.json",
|
||||||
|
"inlineStyleLanguage": "css",
|
||||||
|
"assets": [
|
||||||
|
{
|
||||||
|
"glob": "**/*",
|
||||||
|
"input": "public"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"styles": ["src/styles.css"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
44
apps/dashboard/package.json
Normal file
44
apps/dashboard/package.json
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
{
|
||||||
|
"name": "trading-dashboard",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"scripts": {
|
||||||
|
"ng": "ng",
|
||||||
|
"start": "ng serve",
|
||||||
|
"devvvv": "ng serve --port 5173 --host 0.0.0.0",
|
||||||
|
"build": "ng build",
|
||||||
|
"watch": "ng build --watch --configuration development",
|
||||||
|
"test": "ng test"
|
||||||
|
},
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@angular/animations": "^20.0.0",
|
||||||
|
"@angular/cdk": "^20.0.1",
|
||||||
|
"@angular/common": "^20.0.0",
|
||||||
|
"@angular/compiler": "^20.0.0",
|
||||||
|
"@angular/core": "^20.0.0",
|
||||||
|
"@angular/forms": "^20.0.0",
|
||||||
|
"@angular/material": "^20.0.1",
|
||||||
|
"@angular/platform-browser": "^20.0.0",
|
||||||
|
"@angular/router": "^20.0.0",
|
||||||
|
"rxjs": "~7.8.2",
|
||||||
|
"tslib": "^2.8.1",
|
||||||
|
"zone.js": "~0.15.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@angular/build": "^20.0.0",
|
||||||
|
"@angular/cli": "^20.0.0",
|
||||||
|
"@angular/compiler-cli": "^20.0.0",
|
||||||
|
"@tailwindcss/postcss": "^4.1.8",
|
||||||
|
"@types/jasmine": "~5.1.8",
|
||||||
|
"autoprefixer": "^10.4.21",
|
||||||
|
"jasmine-core": "~5.7.1",
|
||||||
|
"karma": "~6.4.4",
|
||||||
|
"karma-chrome-launcher": "~3.2.0",
|
||||||
|
"karma-coverage": "~2.2.1",
|
||||||
|
"karma-jasmine": "~5.1.0",
|
||||||
|
"karma-jasmine-html-reporter": "~2.1.0",
|
||||||
|
"postcss": "^8.5.4",
|
||||||
|
"tailwindcss": "^4.1.8",
|
||||||
|
"typescript": "~5.8.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
0
apps/dashboard/postcss.config.js
Normal file
0
apps/dashboard/postcss.config.js
Normal file
BIN
apps/dashboard/public/favicon.ico
Normal file
BIN
apps/dashboard/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
0
apps/dashboard/src/App.tsx
Normal file
0
apps/dashboard/src/App.tsx
Normal file
19
apps/dashboard/src/app/app.config.ts
Normal file
19
apps/dashboard/src/app/app.config.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import {
|
||||||
|
ApplicationConfig,
|
||||||
|
provideBrowserGlobalErrorListeners,
|
||||||
|
provideZonelessChangeDetection,
|
||||||
|
} from '@angular/core';
|
||||||
|
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
import { routes } from './app.routes';
|
||||||
|
|
||||||
|
export const appConfig: ApplicationConfig = {
|
||||||
|
providers: [
|
||||||
|
provideBrowserGlobalErrorListeners(),
|
||||||
|
provideZonelessChangeDetection(),
|
||||||
|
provideRouter(routes),
|
||||||
|
provideHttpClient(),
|
||||||
|
provideAnimationsAsync(),
|
||||||
|
],
|
||||||
|
};
|
||||||
174
apps/dashboard/src/app/app.css
Normal file
174
apps/dashboard/src/app/app.css
Normal file
|
|
@ -0,0 +1,174 @@
|
||||||
|
/* Custom Angular Material integration styles */
|
||||||
|
|
||||||
|
/* Sidenav styles */
|
||||||
|
.mat-sidenav-container {
|
||||||
|
background-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-sidenav {
|
||||||
|
border-radius: 0;
|
||||||
|
width: 16rem;
|
||||||
|
background-color: white !important;
|
||||||
|
border-right: 1px solid #e5e7eb !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Toolbar styles */
|
||||||
|
.mat-toolbar {
|
||||||
|
background-color: white;
|
||||||
|
color: #374151;
|
||||||
|
box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Button styles */
|
||||||
|
.mat-mdc-button.nav-button {
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
justify-content: flex-start;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
margin-bottom: 0.25rem;
|
||||||
|
background-color: transparent;
|
||||||
|
transition: background-color 0.15s ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-button.nav-button:hover {
|
||||||
|
background-color: #f3f4f6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-button.nav-button.bg-blue-50 {
|
||||||
|
background-color: #eff6ff !important;
|
||||||
|
color: #1d4ed8 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Card styles */
|
||||||
|
.mat-mdc-card {
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
|
||||||
|
border: 1px solid #f3f4f6;
|
||||||
|
background-color: white !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tab styles */
|
||||||
|
.mat-mdc-tab-group .mat-mdc-tab-header {
|
||||||
|
border-bottom: 1px solid #e5e7eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-tab-label {
|
||||||
|
color: #6b7280;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-tab-label:hover {
|
||||||
|
color: #111827;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-tab-label-active {
|
||||||
|
color: #2563eb;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Chip styles for status indicators */
|
||||||
|
.mat-mdc-chip-set .mat-mdc-chip {
|
||||||
|
background-color: white;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-green {
|
||||||
|
background-color: #dcfce7 !important;
|
||||||
|
color: #166534 !important;
|
||||||
|
border: 1px solid #bbf7d0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-blue {
|
||||||
|
background-color: #dbeafe !important;
|
||||||
|
color: #1e40af !important;
|
||||||
|
border: 1px solid #bfdbfe !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-chip-active {
|
||||||
|
background-color: #dcfce7;
|
||||||
|
color: #166534;
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
border-radius: 9999px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-chip-medium {
|
||||||
|
background-color: #dbeafe;
|
||||||
|
color: #1e40af;
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
border-radius: 9999px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Table styles */
|
||||||
|
.mat-mdc-table {
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid #f3f4f6;
|
||||||
|
background-color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-header-row {
|
||||||
|
background-color: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-header-cell {
|
||||||
|
font-weight: 500;
|
||||||
|
color: #374151;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-cell {
|
||||||
|
color: #111827;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
padding: 1rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-row:hover {
|
||||||
|
background-color: #f9fafb;
|
||||||
|
transition: background-color 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Custom utility classes for the dashboard */
|
||||||
|
.portfolio-card {
|
||||||
|
background-color: white !important;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
|
||||||
|
border: 1px solid #f3f4f6;
|
||||||
|
padding: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-value {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-label {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: #6b7280;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-change-positive {
|
||||||
|
color: #16a34a;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-change-negative {
|
||||||
|
color: #dc2626;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Responsive styles */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.mat-sidenav {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hide-mobile {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
67
apps/dashboard/src/app/app.html
Normal file
67
apps/dashboard/src/app/app.html
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
<!-- Trading Dashboard App -->
|
||||||
|
<div class="app-layout">
|
||||||
|
<!-- Sidebar -->
|
||||||
|
<app-sidebar [opened]="sidenavOpened()" (navigationItemClick)="onNavigationClick($event)"></app-sidebar>
|
||||||
|
|
||||||
|
<!-- Main Content Area -->
|
||||||
|
<div class="main-content" [class.main-content-closed]="!sidenavOpened()">
|
||||||
|
<!-- Top Navigation Bar -->
|
||||||
|
<mat-toolbar class="top-toolbar">
|
||||||
|
<button mat-icon-button (click)="toggleSidenav()" class="mr-2">
|
||||||
|
<mat-icon>menu</mat-icon>
|
||||||
|
</button> <span class="text-lg font-semibold text-gray-800">{{ title }}</span>
|
||||||
|
<span class="spacer"></span>
|
||||||
|
<app-notifications></app-notifications>
|
||||||
|
<button mat-icon-button>
|
||||||
|
<mat-icon>account_circle</mat-icon>
|
||||||
|
</button>
|
||||||
|
</mat-toolbar>
|
||||||
|
|
||||||
|
<!-- Page Content -->
|
||||||
|
<div class="page-content">
|
||||||
|
<router-outlet></router-outlet>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.app-layout {
|
||||||
|
display: flex;
|
||||||
|
height: 100vh;
|
||||||
|
background-color: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-content {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
margin-left: 256px; /* Width of sidebar */
|
||||||
|
transition: margin-left 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-content-closed {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.top-toolbar {
|
||||||
|
background-color: white;
|
||||||
|
border-bottom: 1px solid #e5e7eb;
|
||||||
|
box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
.spacer {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-content {
|
||||||
|
flex: 1;
|
||||||
|
padding: 1.5rem;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.main-content {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
18
apps/dashboard/src/app/app.routes.ts
Normal file
18
apps/dashboard/src/app/app.routes.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { Routes } from '@angular/router';
|
||||||
|
import { DashboardComponent } from './pages/dashboard/dashboard.component';
|
||||||
|
import { MarketDataComponent } from './pages/market-data/market-data.component';
|
||||||
|
import { PortfolioComponent } from './pages/portfolio/portfolio.component';
|
||||||
|
import { RiskManagementComponent } from './pages/risk-management/risk-management.component';
|
||||||
|
import { SettingsComponent } from './pages/settings/settings.component';
|
||||||
|
import { StrategiesComponent } from './pages/strategies/strategies.component';
|
||||||
|
|
||||||
|
export const routes: Routes = [
|
||||||
|
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
|
||||||
|
{ path: 'dashboard', component: DashboardComponent },
|
||||||
|
{ path: 'market-data', component: MarketDataComponent },
|
||||||
|
{ path: 'portfolio', component: PortfolioComponent },
|
||||||
|
{ path: 'strategies', component: StrategiesComponent },
|
||||||
|
{ path: 'risk-management', component: RiskManagementComponent },
|
||||||
|
{ path: 'settings', component: SettingsComponent },
|
||||||
|
{ path: '**', redirectTo: '/dashboard' },
|
||||||
|
];
|
||||||
0
apps/dashboard/src/app/app.scss
Normal file
0
apps/dashboard/src/app/app.scss
Normal file
25
apps/dashboard/src/app/app.spec.ts
Normal file
25
apps/dashboard/src/app/app.spec.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
import { provideZonelessChangeDetection } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { App } from './app';
|
||||||
|
|
||||||
|
describe('App', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [App],
|
||||||
|
providers: [provideZonelessChangeDetection()],
|
||||||
|
}).compileComponents();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create the app', () => {
|
||||||
|
const fixture = TestBed.createComponent(App);
|
||||||
|
const app = fixture.componentInstance;
|
||||||
|
expect(app).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should render title', () => {
|
||||||
|
const fixture = TestBed.createComponent(App);
|
||||||
|
fixture.detectChanges();
|
||||||
|
const compiled = fixture.nativeElement as HTMLElement;
|
||||||
|
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, trading-dashboard');
|
||||||
|
});
|
||||||
|
});
|
||||||
40
apps/dashboard/src/app/app.ts
Normal file
40
apps/dashboard/src/app/app.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, signal } from '@angular/core';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatChipsModule } from '@angular/material/chips';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatSidenavModule } from '@angular/material/sidenav';
|
||||||
|
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||||
|
import { RouterOutlet } from '@angular/router';
|
||||||
|
import { NotificationsComponent } from './components/notifications/notifications';
|
||||||
|
import { SidebarComponent } from './components/sidebar/sidebar.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-root',
|
||||||
|
imports: [
|
||||||
|
RouterOutlet,
|
||||||
|
CommonModule,
|
||||||
|
MatSidenavModule,
|
||||||
|
MatToolbarModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatChipsModule,
|
||||||
|
SidebarComponent,
|
||||||
|
NotificationsComponent,
|
||||||
|
],
|
||||||
|
templateUrl: './app.html',
|
||||||
|
styleUrl: './app.css',
|
||||||
|
})
|
||||||
|
export class App {
|
||||||
|
protected title = 'Trading Dashboard';
|
||||||
|
protected sidenavOpened = signal(true);
|
||||||
|
|
||||||
|
toggleSidenav() {
|
||||||
|
this.sidenavOpened.set(!this.sidenavOpened());
|
||||||
|
}
|
||||||
|
|
||||||
|
onNavigationClick(route: string) {
|
||||||
|
// Handle navigation if needed
|
||||||
|
console.log('Navigating to:', route);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
::ng-deep .notification-menu {
|
||||||
|
width: 380px;
|
||||||
|
max-width: 90vw;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-header {
|
||||||
|
padding: 12px 16px !important;
|
||||||
|
height: auto !important;
|
||||||
|
line-height: normal !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-empty {
|
||||||
|
padding: 16px !important;
|
||||||
|
height: auto !important;
|
||||||
|
line-height: normal !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-item {
|
||||||
|
padding: 12px 16px !important;
|
||||||
|
height: auto !important;
|
||||||
|
line-height: normal !important;
|
||||||
|
white-space: normal !important;
|
||||||
|
border-left: 3px solid transparent;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-item:hover {
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-item.unread {
|
||||||
|
background-color: #f0f9ff;
|
||||||
|
border-left-color: #0ea5e9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-item.unread .font-medium {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.line-clamp-2 {
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-line-clamp: 2;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,75 @@
|
||||||
|
<button
|
||||||
|
mat-icon-button
|
||||||
|
[matMenuTriggerFor]="notificationMenu"
|
||||||
|
[matBadge]="unreadCount"
|
||||||
|
[matBadgeHidden]="unreadCount === 0"
|
||||||
|
matBadgeColor="warn"
|
||||||
|
matBadgeSize="small">
|
||||||
|
<mat-icon>notifications</mat-icon>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<mat-menu #notificationMenu="matMenu" class="notification-menu">
|
||||||
|
<div mat-menu-item disabled class="notification-header">
|
||||||
|
<div class="flex items-center justify-between w-full px-2">
|
||||||
|
<span class="font-semibold">Notifications</span>
|
||||||
|
@if (notifications.length > 0) {
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button mat-button (click)="markAllAsRead()" class="text-xs">
|
||||||
|
Mark all read
|
||||||
|
</button>
|
||||||
|
<button mat-button (click)="clearAll()" class="text-xs">
|
||||||
|
Clear all
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<mat-divider></mat-divider>
|
||||||
|
|
||||||
|
@if (notifications.length === 0) {
|
||||||
|
<div mat-menu-item disabled class="notification-empty">
|
||||||
|
<div class="text-center py-4 text-gray-500">
|
||||||
|
<mat-icon class="text-2xl">notifications_none</mat-icon>
|
||||||
|
<p class="mt-1 text-sm">No notifications</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
@for (notification of notifications.slice(0, 5); track notification.id) {
|
||||||
|
<div
|
||||||
|
mat-menu-item
|
||||||
|
class="notification-item"
|
||||||
|
[class.unread]="!notification.read"
|
||||||
|
(click)="markAsRead(notification)">
|
||||||
|
<div class="flex items-start gap-3 w-full">
|
||||||
|
<mat-icon [class]="getNotificationColor(notification.type)" class="mt-1">
|
||||||
|
{{ getNotificationIcon(notification.type) }}
|
||||||
|
</mat-icon>
|
||||||
|
<div class="flex-1 min-w-0">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<p class="font-medium text-sm truncate">{{ notification.title }}</p>
|
||||||
|
<button
|
||||||
|
mat-icon-button
|
||||||
|
(click)="clearNotification(notification); $event.stopPropagation()"
|
||||||
|
class="text-gray-400 hover:text-gray-600 ml-2">
|
||||||
|
<mat-icon class="text-lg">close</mat-icon>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="text-gray-600 text-xs mt-1 line-clamp-2">{{ notification.message }}</p>
|
||||||
|
<p class="text-gray-400 text-xs mt-1">{{ formatTime(notification.timestamp) }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@if (!$last) {
|
||||||
|
<mat-divider></mat-divider>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (notifications.length > 5) {
|
||||||
|
<mat-divider></mat-divider>
|
||||||
|
<div mat-menu-item disabled class="text-center text-sm text-gray-500">
|
||||||
|
{{ notifications.length - 5 }} more notifications...
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</mat-menu>
|
||||||
100
apps/dashboard/src/app/components/notifications/notifications.ts
Normal file
100
apps/dashboard/src/app/components/notifications/notifications.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, inject } from '@angular/core';
|
||||||
|
import { MatBadgeModule } from '@angular/material/badge';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatDividerModule } from '@angular/material/divider';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatListModule } from '@angular/material/list';
|
||||||
|
import { MatMenuModule } from '@angular/material/menu';
|
||||||
|
import { Notification, NotificationService } from '../../services/notification.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-notifications',
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatBadgeModule,
|
||||||
|
MatMenuModule,
|
||||||
|
MatListModule,
|
||||||
|
MatDividerModule,
|
||||||
|
],
|
||||||
|
templateUrl: './notifications.html',
|
||||||
|
styleUrl: './notifications.css',
|
||||||
|
})
|
||||||
|
export class NotificationsComponent {
|
||||||
|
private notificationService = inject(NotificationService);
|
||||||
|
|
||||||
|
get notifications() {
|
||||||
|
return this.notificationService.notifications();
|
||||||
|
}
|
||||||
|
|
||||||
|
get unreadCount() {
|
||||||
|
return this.notificationService.unreadCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
markAsRead(notification: Notification) {
|
||||||
|
this.notificationService.markAsRead(notification.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
markAllAsRead() {
|
||||||
|
this.notificationService.markAllAsRead();
|
||||||
|
}
|
||||||
|
|
||||||
|
clearNotification(notification: Notification) {
|
||||||
|
this.notificationService.clearNotification(notification.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
clearAll() {
|
||||||
|
this.notificationService.clearAllNotifications();
|
||||||
|
}
|
||||||
|
|
||||||
|
getNotificationIcon(type: string): string {
|
||||||
|
switch (type) {
|
||||||
|
case 'error':
|
||||||
|
return 'error';
|
||||||
|
case 'warning':
|
||||||
|
return 'warning';
|
||||||
|
case 'success':
|
||||||
|
return 'check_circle';
|
||||||
|
case 'info':
|
||||||
|
default:
|
||||||
|
return 'info';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getNotificationColor(type: string): string {
|
||||||
|
switch (type) {
|
||||||
|
case 'error':
|
||||||
|
return 'text-red-600';
|
||||||
|
case 'warning':
|
||||||
|
return 'text-yellow-600';
|
||||||
|
case 'success':
|
||||||
|
return 'text-green-600';
|
||||||
|
case 'info':
|
||||||
|
default:
|
||||||
|
return 'text-blue-600';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
formatTime(timestamp: Date): string {
|
||||||
|
const now = new Date();
|
||||||
|
const diff = now.getTime() - timestamp.getTime();
|
||||||
|
const minutes = Math.floor(diff / 60000);
|
||||||
|
|
||||||
|
if (minutes < 1) {
|
||||||
|
return 'Just now';
|
||||||
|
}
|
||||||
|
if (minutes < 60) {
|
||||||
|
return `${minutes}m ago`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hours = Math.floor(minutes / 60);
|
||||||
|
if (hours < 24) {
|
||||||
|
return `${hours}h ago`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const days = Math.floor(hours / 24);
|
||||||
|
return `${days}d ago`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
/* Sidebar specific styles */
|
||||||
|
.sidebar {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 16rem; /* 256px */
|
||||||
|
height: 100vh;
|
||||||
|
background-color: white;
|
||||||
|
border-right: 1px solid #e5e7eb;
|
||||||
|
transform: translateX(0);
|
||||||
|
transition: transform 0.3s ease-in-out;
|
||||||
|
z-index: 1000;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar-closed {
|
||||||
|
transform: translateX(-100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-button {
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
justify-content: flex-start;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
margin-bottom: 0.25rem;
|
||||||
|
background-color: transparent;
|
||||||
|
transition: background-color 0.15s ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-button:hover {
|
||||||
|
background-color: #f3f4f6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-button.bg-blue-50 {
|
||||||
|
background-color: #eff6ff !important;
|
||||||
|
color: #1d4ed8 !important;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
<!-- Sidebar Navigation -->
|
||||||
|
<aside class="sidebar" [class.sidebar-closed]="!opened()">
|
||||||
|
<!-- Logo/Brand -->
|
||||||
|
<div class="p-6 border-b border-gray-200">
|
||||||
|
<h2 class="text-xl font-bold text-gray-900">
|
||||||
|
📈 Trading Bot
|
||||||
|
</h2>
|
||||||
|
<p class="text-sm text-gray-600 mt-1">
|
||||||
|
Real-time Dashboard
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Navigation Menu -->
|
||||||
|
<nav class="p-6">
|
||||||
|
<div class="space-y-2">
|
||||||
|
@for (item of navigationItems; track item.route) {
|
||||||
|
<button
|
||||||
|
mat-button
|
||||||
|
class="nav-button"
|
||||||
|
[class.bg-blue-50]="item.active"
|
||||||
|
[class.text-blue-700]="item.active"
|
||||||
|
[class.text-gray-600]="!item.active"
|
||||||
|
(click)="onNavigationClick(item.route)">
|
||||||
|
<mat-icon class="mr-3">{{ item.icon }}</mat-icon>
|
||||||
|
{{ item.label }}
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
</aside>
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, input, output } from '@angular/core';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatSidenavModule } from '@angular/material/sidenav';
|
||||||
|
import { NavigationEnd, Router } from '@angular/router';
|
||||||
|
import { filter } from 'rxjs/operators';
|
||||||
|
|
||||||
|
export interface NavigationItem {
|
||||||
|
label: string;
|
||||||
|
icon: string;
|
||||||
|
route: string;
|
||||||
|
active?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-sidebar',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule, MatSidenavModule, MatButtonModule, MatIconModule],
|
||||||
|
templateUrl: './sidebar.component.html',
|
||||||
|
styleUrl: './sidebar.component.css',
|
||||||
|
})
|
||||||
|
export class SidebarComponent {
|
||||||
|
opened = input<boolean>(true);
|
||||||
|
navigationItemClick = output<string>();
|
||||||
|
|
||||||
|
protected navigationItems: NavigationItem[] = [
|
||||||
|
{ label: 'Dashboard', icon: 'dashboard', route: '/dashboard', active: true },
|
||||||
|
{ label: 'Market Data', icon: 'trending_up', route: '/market-data' },
|
||||||
|
{ label: 'Portfolio', icon: 'account_balance_wallet', route: '/portfolio' },
|
||||||
|
{ label: 'Strategies', icon: 'psychology', route: '/strategies' },
|
||||||
|
{ label: 'Risk Management', icon: 'security', route: '/risk-management' },
|
||||||
|
{ label: 'Settings', icon: 'settings', route: '/settings' },
|
||||||
|
];
|
||||||
|
|
||||||
|
constructor(private router: Router) {
|
||||||
|
// Listen to route changes to update active state
|
||||||
|
this.router.events
|
||||||
|
.pipe(filter(event => event instanceof NavigationEnd))
|
||||||
|
.subscribe((event: NavigationEnd) => {
|
||||||
|
this.updateActiveRoute(event.urlAfterRedirects);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onNavigationClick(route: string) {
|
||||||
|
this.navigationItemClick.emit(route);
|
||||||
|
this.router.navigate([route]);
|
||||||
|
this.updateActiveRoute(route);
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateActiveRoute(currentRoute: string) {
|
||||||
|
this.navigationItems.forEach(item => {
|
||||||
|
item.active = item.route === currentRoute;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,48 @@
|
||||||
|
/* Dashboard specific styles */
|
||||||
|
.portfolio-card {
|
||||||
|
background-color: white !important;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
|
||||||
|
border: 1px solid #f3f4f6;
|
||||||
|
padding: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-value {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-label {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: #6b7280;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-change-positive {
|
||||||
|
color: #16a34a;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-change-negative {
|
||||||
|
color: #dc2626;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-chip-active {
|
||||||
|
background-color: #dcfce7;
|
||||||
|
color: #166534;
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
border-radius: 9999px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-chip-medium {
|
||||||
|
background-color: #dbeafe;
|
||||||
|
color: #1e40af;
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
border-radius: 9999px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
154
apps/dashboard/src/app/pages/dashboard/dashboard.component.html
Normal file
154
apps/dashboard/src/app/pages/dashboard/dashboard.component.html
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
<!-- Portfolio Summary Cards -->
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
|
||||||
|
<!-- Total Portfolio Value -->
|
||||||
|
<mat-card class="portfolio-card">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="metric-label">Portfolio Value</p>
|
||||||
|
<p class="metric-value text-gray-900">
|
||||||
|
${{ portfolioValue().toLocaleString('en-US', {minimumFractionDigits: 2}) }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-blue-600 text-3xl">account_balance_wallet</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<!-- Day Change -->
|
||||||
|
<mat-card class="portfolio-card">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="metric-label">Day Change</p>
|
||||||
|
<p class="metric-value"
|
||||||
|
[class.metric-change-positive]="dayChange() > 0"
|
||||||
|
[class.metric-change-negative]="dayChange() < 0">
|
||||||
|
${{ dayChange().toLocaleString('en-US', {minimumFractionDigits: 2}) }}
|
||||||
|
</p>
|
||||||
|
<p class="text-sm font-medium"
|
||||||
|
[class.metric-change-positive]="dayChangePercent() > 0"
|
||||||
|
[class.metric-change-negative]="dayChangePercent() < 0">
|
||||||
|
{{ dayChangePercent() > 0 ? '+' : '' }}{{ dayChangePercent().toFixed(2) }}%
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon
|
||||||
|
class="text-3xl"
|
||||||
|
[class.metric-change-positive]="dayChange() > 0"
|
||||||
|
[class.metric-change-negative]="dayChange() < 0">
|
||||||
|
{{ dayChange() > 0 ? 'trending_up' : 'trending_down' }}
|
||||||
|
</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<!-- Active Strategies -->
|
||||||
|
<mat-card class="portfolio-card">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="metric-label">Active Strategies</p>
|
||||||
|
<p class="metric-value text-gray-900">3</p>
|
||||||
|
<span class="status-chip-active">Running</span>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-purple-600 text-3xl">psychology</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<!-- Risk Level -->
|
||||||
|
<mat-card class="portfolio-card">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="metric-label">Risk Level</p>
|
||||||
|
<p class="metric-value text-green-600">Low</p>
|
||||||
|
<span class="status-chip-medium">Moderate</span>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-green-600 text-3xl">security</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Market Data Table -->
|
||||||
|
<mat-card class="p-6 mb-6">
|
||||||
|
<div class="flex items-center justify-between mb-4">
|
||||||
|
<h3 class="text-lg font-semibold text-gray-900">Market Watchlist</h3>
|
||||||
|
<button mat-raised-button color="primary">
|
||||||
|
<mat-icon>refresh</mat-icon>
|
||||||
|
Refresh
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table mat-table [dataSource]="marketData()" class="mat-elevation-z0 w-full">
|
||||||
|
<!-- Symbol Column -->
|
||||||
|
<ng-container matColumnDef="symbol">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="font-medium text-gray-900">Symbol</th>
|
||||||
|
<td mat-cell *matCellDef="let stock" class="font-semibold text-gray-900">{{ stock.symbol }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Price Column -->
|
||||||
|
<ng-container matColumnDef="price">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Price</th>
|
||||||
|
<td mat-cell *matCellDef="let stock" class="text-right font-medium text-gray-900">
|
||||||
|
${{ stock.price.toFixed(2) }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Change Column -->
|
||||||
|
<ng-container matColumnDef="change">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Change</th>
|
||||||
|
<td mat-cell *matCellDef="let stock"
|
||||||
|
class="text-right font-medium"
|
||||||
|
[class.text-green-600]="stock.change > 0"
|
||||||
|
[class.text-red-600]="stock.change < 0">
|
||||||
|
{{ stock.change > 0 ? '+' : '' }}${{ stock.change.toFixed(2) }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Change Percent Column -->
|
||||||
|
<ng-container matColumnDef="changePercent">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Change %</th>
|
||||||
|
<td mat-cell *matCellDef="let stock"
|
||||||
|
class="text-right font-medium"
|
||||||
|
[class.text-green-600]="stock.changePercent > 0"
|
||||||
|
[class.text-red-600]="stock.changePercent < 0">
|
||||||
|
{{ stock.changePercent > 0 ? '+' : '' }}{{ stock.changePercent.toFixed(2) }}%
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||||
|
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<!-- Tabs for Additional Content -->
|
||||||
|
<mat-tab-group>
|
||||||
|
<mat-tab label="Chart">
|
||||||
|
<div class="p-6">
|
||||||
|
<mat-card class="p-6 h-96 flex items-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem;">show_chart</mat-icon>
|
||||||
|
<p class="mb-4">Chart visualization will be implemented here</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab label="Orders">
|
||||||
|
<div class="p-6">
|
||||||
|
<mat-card class="p-6 h-96 flex items-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem;">receipt_long</mat-icon>
|
||||||
|
<p class="mb-4">Order history and management will be implemented here</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab label="Analytics">
|
||||||
|
<div class="p-6">
|
||||||
|
<mat-card class="p-6 h-96 flex items-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem;">analytics</mat-icon>
|
||||||
|
<p class="mb-4">Advanced analytics and performance metrics will be implemented here</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
</mat-tab-group>
|
||||||
|
|
@ -0,0 +1,44 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, signal } from '@angular/core';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatTableModule } from '@angular/material/table';
|
||||||
|
import { MatTabsModule } from '@angular/material/tabs';
|
||||||
|
|
||||||
|
export interface MarketDataItem {
|
||||||
|
symbol: string;
|
||||||
|
price: number;
|
||||||
|
change: number;
|
||||||
|
changePercent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-dashboard',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
MatCardModule,
|
||||||
|
MatTabsModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatTableModule,
|
||||||
|
],
|
||||||
|
templateUrl: './dashboard.component.html',
|
||||||
|
styleUrl: './dashboard.component.css',
|
||||||
|
})
|
||||||
|
export class DashboardComponent {
|
||||||
|
// Mock data for the dashboard
|
||||||
|
protected marketData = signal<MarketDataItem[]>([
|
||||||
|
{ symbol: 'AAPL', price: 192.53, change: 2.41, changePercent: 1.27 },
|
||||||
|
{ symbol: 'GOOGL', price: 138.21, change: -1.82, changePercent: -1.3 },
|
||||||
|
{ symbol: 'MSFT', price: 378.85, change: 4.12, changePercent: 1.1 },
|
||||||
|
{ symbol: 'TSLA', price: 248.42, change: -3.21, changePercent: -1.28 },
|
||||||
|
]);
|
||||||
|
|
||||||
|
protected portfolioValue = signal(125420.5);
|
||||||
|
protected dayChange = signal(2341.2);
|
||||||
|
protected dayChangePercent = signal(1.9);
|
||||||
|
|
||||||
|
protected displayedColumns: string[] = ['symbol', 'price', 'change', 'changePercent'];
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
/* Market Data specific styles */
|
||||||
|
|
@ -0,0 +1,172 @@
|
||||||
|
<div class="space-y-6"> <!-- Page Header -->
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-bold text-gray-900">Market Data</h1>
|
||||||
|
<p class="text-gray-600 mt-1">Real-time market information and analytics</p>
|
||||||
|
</div>
|
||||||
|
<button mat-raised-button color="primary" (click)="refreshData()" [disabled]="isLoading()">
|
||||||
|
<mat-icon>refresh</mat-icon>
|
||||||
|
@if (isLoading()) {
|
||||||
|
<mat-spinner diameter="20" class="mr-2"></mat-spinner>
|
||||||
|
}
|
||||||
|
Refresh Data
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Market Overview Cards -->
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Market Status</p>
|
||||||
|
<p class="text-lg font-semibold text-green-600">Open</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-green-600 text-3xl">schedule</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Active Instruments</p>
|
||||||
|
<p class="text-lg font-semibold text-gray-900">{{ marketData().length }}</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-blue-600 text-3xl">trending_up</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between"> <div>
|
||||||
|
<p class="text-sm text-gray-600">Last Update</p>
|
||||||
|
<p class="text-lg font-semibold text-gray-900">{{ currentTime() }}</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-purple-600 text-3xl">access_time</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Market Data Table -->
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between mb-4">
|
||||||
|
<h3 class="text-lg font-semibold text-gray-900">Live Market Data</h3>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button mat-button>
|
||||||
|
<mat-icon>filter_list</mat-icon>
|
||||||
|
Filter
|
||||||
|
</button>
|
||||||
|
<button mat-button>
|
||||||
|
<mat-icon>file_download</mat-icon>
|
||||||
|
Export
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@if (isLoading()) {
|
||||||
|
<div class="flex justify-center items-center py-8">
|
||||||
|
<mat-spinner diameter="40"></mat-spinner>
|
||||||
|
<span class="ml-3 text-gray-600">Loading market data...</span>
|
||||||
|
</div>
|
||||||
|
} @else if (error()) {
|
||||||
|
<div class="text-center py-8">
|
||||||
|
<mat-icon class="text-red-500 text-4xl">error</mat-icon>
|
||||||
|
<p class="text-red-600 mt-2">{{ error() }}</p>
|
||||||
|
<button mat-button color="primary" (click)="refreshData()" class="mt-2">
|
||||||
|
<mat-icon>refresh</mat-icon>
|
||||||
|
Try Again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table mat-table [dataSource]="marketData()" class="mat-elevation-z0 w-full">
|
||||||
|
<!-- Symbol Column -->
|
||||||
|
<ng-container matColumnDef="symbol">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="font-medium text-gray-900">Symbol</th>
|
||||||
|
<td mat-cell *matCellDef="let stock" class="font-semibold text-gray-900">{{ stock.symbol }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Price Column -->
|
||||||
|
<ng-container matColumnDef="price">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Price</th>
|
||||||
|
<td mat-cell *matCellDef="let stock" class="text-right font-medium text-gray-900">
|
||||||
|
${{ stock.price.toFixed(2) }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Change Column -->
|
||||||
|
<ng-container matColumnDef="change">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Change</th>
|
||||||
|
<td mat-cell *matCellDef="let stock"
|
||||||
|
class="text-right font-medium"
|
||||||
|
[class.text-green-600]="stock.change > 0"
|
||||||
|
[class.text-red-600]="stock.change < 0">
|
||||||
|
{{ stock.change > 0 ? '+' : '' }}${{ stock.change.toFixed(2) }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Change Percent Column -->
|
||||||
|
<ng-container matColumnDef="changePercent">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Change %</th>
|
||||||
|
<td mat-cell *matCellDef="let stock"
|
||||||
|
class="text-right font-medium"
|
||||||
|
[class.text-green-600]="stock.changePercent > 0"
|
||||||
|
[class.text-red-600]="stock.changePercent < 0">
|
||||||
|
{{ stock.changePercent > 0 ? '+' : '' }}{{ stock.changePercent.toFixed(2) }}%
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Volume Column -->
|
||||||
|
<ng-container matColumnDef="volume">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Volume</th>
|
||||||
|
<td mat-cell *matCellDef="let stock" class="text-right text-gray-600">
|
||||||
|
{{ stock.volume.toLocaleString() }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Market Cap Column -->
|
||||||
|
<ng-container matColumnDef="marketCap">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Market Cap</th>
|
||||||
|
<td mat-cell *matCellDef="let stock" class="text-right text-gray-600">
|
||||||
|
${{ stock.marketCap }}
|
||||||
|
</td>
|
||||||
|
</ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||||
|
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<!-- Market Analytics Tabs -->
|
||||||
|
<mat-tab-group>
|
||||||
|
<mat-tab label="Technical Analysis">
|
||||||
|
<div class="p-6">
|
||||||
|
<mat-card class="p-6 h-96 flex items-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem;">bar_chart</mat-icon>
|
||||||
|
<p class="mb-4">Technical analysis charts and indicators will be implemented here</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab label="Market Trends">
|
||||||
|
<div class="p-6">
|
||||||
|
<mat-card class="p-6 h-96 flex items-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem;">timeline</mat-icon>
|
||||||
|
<p class="mb-4">Market trends and sector analysis will be implemented here</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab label="News & Events">
|
||||||
|
<div class="p-6">
|
||||||
|
<mat-card class="p-6 h-96 flex items-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem;">article</mat-icon>
|
||||||
|
<p class="mb-4">Market news and economic events will be implemented here</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
</mat-tab-group>
|
||||||
|
</div>
|
||||||
|
|
@ -0,0 +1,205 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, inject, OnDestroy, OnInit, signal } from '@angular/core';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||||
|
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||||
|
import { MatTableModule } from '@angular/material/table';
|
||||||
|
import { MatTabsModule } from '@angular/material/tabs';
|
||||||
|
import { interval, Subscription } from 'rxjs';
|
||||||
|
import { ApiService } from '../../services/api.service';
|
||||||
|
import { WebSocketService } from '../../services/websocket.service';
|
||||||
|
|
||||||
|
export interface ExtendedMarketData {
|
||||||
|
symbol: string;
|
||||||
|
price: number;
|
||||||
|
change: number;
|
||||||
|
changePercent: number;
|
||||||
|
volume: number;
|
||||||
|
marketCap: string;
|
||||||
|
high52Week: number;
|
||||||
|
low52Week: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-market-data',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
MatCardModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatTableModule,
|
||||||
|
MatTabsModule,
|
||||||
|
MatProgressSpinnerModule,
|
||||||
|
MatSnackBarModule,
|
||||||
|
],
|
||||||
|
templateUrl: './market-data.component.html',
|
||||||
|
styleUrl: './market-data.component.css',
|
||||||
|
})
|
||||||
|
export class MarketDataComponent implements OnInit, OnDestroy {
|
||||||
|
private apiService = inject(ApiService);
|
||||||
|
private webSocketService = inject(WebSocketService);
|
||||||
|
private snackBar = inject(MatSnackBar);
|
||||||
|
private subscriptions: Subscription[] = [];
|
||||||
|
|
||||||
|
protected marketData = signal<ExtendedMarketData[]>([]);
|
||||||
|
protected currentTime = signal<string>(new Date().toLocaleTimeString());
|
||||||
|
protected isLoading = signal<boolean>(true);
|
||||||
|
protected error = signal<string | null>(null);
|
||||||
|
protected displayedColumns: string[] = [
|
||||||
|
'symbol',
|
||||||
|
'price',
|
||||||
|
'change',
|
||||||
|
'changePercent',
|
||||||
|
'volume',
|
||||||
|
'marketCap',
|
||||||
|
];
|
||||||
|
ngOnInit() {
|
||||||
|
// Update time every second
|
||||||
|
const timeSubscription = interval(1000).subscribe(() => {
|
||||||
|
this.currentTime.set(new Date().toLocaleTimeString());
|
||||||
|
});
|
||||||
|
this.subscriptions.push(timeSubscription);
|
||||||
|
|
||||||
|
// Load initial market data
|
||||||
|
this.loadMarketData();
|
||||||
|
|
||||||
|
// Subscribe to real-time market data updates
|
||||||
|
const wsSubscription = this.webSocketService.getMarketDataUpdates().subscribe({
|
||||||
|
next: update => {
|
||||||
|
this.updateMarketData(update);
|
||||||
|
},
|
||||||
|
error: err => {
|
||||||
|
console.error('WebSocket market data error:', err);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.subscriptions.push(wsSubscription);
|
||||||
|
|
||||||
|
// Fallback: Refresh market data every 30 seconds if WebSocket fails
|
||||||
|
const dataSubscription = interval(30000).subscribe(() => {
|
||||||
|
if (!this.webSocketService.isConnected()) {
|
||||||
|
this.loadMarketData();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.subscriptions.push(dataSubscription);
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy() {
|
||||||
|
this.subscriptions.forEach(sub => sub.unsubscribe());
|
||||||
|
}
|
||||||
|
private loadMarketData() {
|
||||||
|
this.apiService.getMarketData().subscribe({
|
||||||
|
next: response => {
|
||||||
|
// Convert MarketData to ExtendedMarketData with mock extended properties
|
||||||
|
const extendedData: ExtendedMarketData[] = response.data.map(item => ({
|
||||||
|
...item,
|
||||||
|
marketCap: this.getMockMarketCap(item.symbol),
|
||||||
|
high52Week: item.price * 1.3, // Mock 52-week high (30% above current)
|
||||||
|
low52Week: item.price * 0.7, // Mock 52-week low (30% below current)
|
||||||
|
}));
|
||||||
|
|
||||||
|
this.marketData.set(extendedData);
|
||||||
|
this.isLoading.set(false);
|
||||||
|
this.error.set(null);
|
||||||
|
},
|
||||||
|
error: err => {
|
||||||
|
console.error('Failed to load market data:', err);
|
||||||
|
this.error.set('Failed to load market data');
|
||||||
|
this.isLoading.set(false);
|
||||||
|
this.snackBar.open('Failed to load market data', 'Dismiss', { duration: 5000 });
|
||||||
|
|
||||||
|
// Use mock data as fallback
|
||||||
|
this.marketData.set(this.getMockData());
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private getMockMarketCap(symbol: string): string {
|
||||||
|
const marketCaps: { [key: string]: string } = {
|
||||||
|
AAPL: '2.98T',
|
||||||
|
GOOGL: '1.78T',
|
||||||
|
MSFT: '3.08T',
|
||||||
|
TSLA: '789.2B',
|
||||||
|
AMZN: '1.59T',
|
||||||
|
};
|
||||||
|
return marketCaps[symbol] || '1.00T';
|
||||||
|
}
|
||||||
|
|
||||||
|
private getMockData(): ExtendedMarketData[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
symbol: 'AAPL',
|
||||||
|
price: 192.53,
|
||||||
|
change: 2.41,
|
||||||
|
changePercent: 1.27,
|
||||||
|
volume: 45230000,
|
||||||
|
marketCap: '2.98T',
|
||||||
|
high52Week: 199.62,
|
||||||
|
low52Week: 164.08,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
symbol: 'GOOGL',
|
||||||
|
price: 2847.56,
|
||||||
|
change: -12.34,
|
||||||
|
changePercent: -0.43,
|
||||||
|
volume: 12450000,
|
||||||
|
marketCap: '1.78T',
|
||||||
|
high52Week: 3030.93,
|
||||||
|
low52Week: 2193.62,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
symbol: 'MSFT',
|
||||||
|
price: 415.26,
|
||||||
|
change: 8.73,
|
||||||
|
changePercent: 2.15,
|
||||||
|
volume: 23180000,
|
||||||
|
marketCap: '3.08T',
|
||||||
|
high52Week: 468.35,
|
||||||
|
low52Week: 309.45,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
symbol: 'TSLA',
|
||||||
|
price: 248.5,
|
||||||
|
change: -5.21,
|
||||||
|
changePercent: -2.05,
|
||||||
|
volume: 89760000,
|
||||||
|
marketCap: '789.2B',
|
||||||
|
high52Week: 299.29,
|
||||||
|
low52Week: 152.37,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
symbol: 'AMZN',
|
||||||
|
price: 152.74,
|
||||||
|
change: 3.18,
|
||||||
|
changePercent: 2.12,
|
||||||
|
volume: 34520000,
|
||||||
|
marketCap: '1.59T',
|
||||||
|
high52Week: 170.17,
|
||||||
|
low52Week: 118.35,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
refreshData() {
|
||||||
|
this.isLoading.set(true);
|
||||||
|
this.loadMarketData();
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateMarketData(update: any) {
|
||||||
|
const currentData = this.marketData();
|
||||||
|
const updatedData = currentData.map(item => {
|
||||||
|
if (item.symbol === update.symbol) {
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
price: update.price,
|
||||||
|
change: update.change,
|
||||||
|
changePercent: update.changePercent,
|
||||||
|
volume: update.volume,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return item;
|
||||||
|
});
|
||||||
|
this.marketData.set(updatedData);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
/* Portfolio specific styles */
|
||||||
203
apps/dashboard/src/app/pages/portfolio/portfolio.component.html
Normal file
203
apps/dashboard/src/app/pages/portfolio/portfolio.component.html
Normal file
|
|
@ -0,0 +1,203 @@
|
||||||
|
<div class="space-y-6">
|
||||||
|
<!-- Page Header -->
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-bold text-gray-900">Portfolio</h1>
|
||||||
|
<p class="text-gray-600 mt-1">Manage and monitor your investment portfolio</p>
|
||||||
|
</div>
|
||||||
|
<button mat-raised-button color="primary" (click)="refreshData()" [disabled]="isLoading()">
|
||||||
|
<mat-icon>refresh</mat-icon>
|
||||||
|
@if (isLoading()) {
|
||||||
|
<mat-spinner diameter="20" class="mr-2"></mat-spinner>
|
||||||
|
}
|
||||||
|
Refresh Data
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Portfolio Summary Cards -->
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-4 gap-6">
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Total Value</p>
|
||||||
|
<p class="text-lg font-semibold text-gray-900">${{ portfolioSummary().totalValue.toLocaleString() }}</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-blue-600 text-3xl">account_balance_wallet</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Total P&L</p>
|
||||||
|
<p class="text-lg font-semibold" [class]="getPnLColor(portfolioSummary().totalPnL)">
|
||||||
|
{{ portfolioSummary().totalPnL > 0 ? '+' : '' }}${{ portfolioSummary().totalPnL.toLocaleString() }}
|
||||||
|
({{ portfolioSummary().totalPnLPercent.toFixed(2) }}%)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-green-600 text-3xl" *ngIf="portfolioSummary().totalPnL >= 0">trending_up</mat-icon>
|
||||||
|
<mat-icon class="text-red-600 text-3xl" *ngIf="portfolioSummary().totalPnL < 0">trending_down</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Day Change</p>
|
||||||
|
<p class="text-lg font-semibold" [class]="getPnLColor(portfolioSummary().dayChange)">
|
||||||
|
{{ portfolioSummary().dayChange > 0 ? '+' : '' }}${{ portfolioSummary().dayChange.toLocaleString() }}
|
||||||
|
({{ portfolioSummary().dayChangePercent.toFixed(2) }}%)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-purple-600 text-3xl">today</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Cash Available</p>
|
||||||
|
<p class="text-lg font-semibold text-gray-900">${{ portfolioSummary().cash.toLocaleString() }}</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-yellow-600 text-3xl">attach_money</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Portfolio Tabs -->
|
||||||
|
<mat-tab-group>
|
||||||
|
<mat-tab label="Positions">
|
||||||
|
<div class="p-6">
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between mb-4">
|
||||||
|
<h3 class="text-lg font-semibold text-gray-900">Current Positions</h3>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button mat-button>
|
||||||
|
<mat-icon>add</mat-icon>
|
||||||
|
Add Position
|
||||||
|
</button>
|
||||||
|
<button mat-button>
|
||||||
|
<mat-icon>file_download</mat-icon>
|
||||||
|
Export
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (isLoading()) {
|
||||||
|
<div class="flex justify-center items-center py-8">
|
||||||
|
<mat-spinner diameter="40"></mat-spinner>
|
||||||
|
<span class="ml-3 text-gray-600">Loading portfolio...</span>
|
||||||
|
</div>
|
||||||
|
} @else if (error()) {
|
||||||
|
<div class="text-center py-8">
|
||||||
|
<mat-icon class="text-red-500 text-4xl">error</mat-icon>
|
||||||
|
<p class="text-red-600 mt-2">{{ error() }}</p>
|
||||||
|
<button mat-button color="primary" (click)="refreshData()" class="mt-2">
|
||||||
|
<mat-icon>refresh</mat-icon>
|
||||||
|
Try Again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
} @else if (positions().length === 0) {
|
||||||
|
<div class="text-center py-8 text-gray-500">
|
||||||
|
<mat-icon class="text-4xl">account_balance_wallet</mat-icon>
|
||||||
|
<p class="mt-2">No positions found</p>
|
||||||
|
<button mat-button color="primary" class="mt-2">
|
||||||
|
<mat-icon>add</mat-icon>
|
||||||
|
Add Your First Position
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table mat-table [dataSource]="positions()" class="mat-elevation-z0 w-full">
|
||||||
|
<!-- Symbol Column -->
|
||||||
|
<ng-container matColumnDef="symbol">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="font-medium text-gray-900">Symbol</th>
|
||||||
|
<td mat-cell *matCellDef="let position" class="font-semibold text-gray-900">{{ position.symbol }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Quantity Column -->
|
||||||
|
<ng-container matColumnDef="quantity">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Quantity</th>
|
||||||
|
<td mat-cell *matCellDef="let position" class="text-right text-gray-600">
|
||||||
|
{{ position.quantity.toLocaleString() }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Average Price Column -->
|
||||||
|
<ng-container matColumnDef="avgPrice">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Avg Price</th>
|
||||||
|
<td mat-cell *matCellDef="let position" class="text-right text-gray-600">
|
||||||
|
${{ position.avgPrice.toFixed(2) }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Current Price Column -->
|
||||||
|
<ng-container matColumnDef="currentPrice">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Current Price</th>
|
||||||
|
<td mat-cell *matCellDef="let position" class="text-right font-medium text-gray-900">
|
||||||
|
${{ position.currentPrice.toFixed(2) }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Market Value Column -->
|
||||||
|
<ng-container matColumnDef="marketValue">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Market Value</th>
|
||||||
|
<td mat-cell *matCellDef="let position" class="text-right font-medium text-gray-900">
|
||||||
|
${{ position.marketValue.toLocaleString() }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Unrealized P&L Column -->
|
||||||
|
<ng-container matColumnDef="unrealizedPnL">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Unrealized P&L</th>
|
||||||
|
<td mat-cell *matCellDef="let position"
|
||||||
|
class="text-right font-medium"
|
||||||
|
[class]="getPnLColor(position.unrealizedPnL)">
|
||||||
|
{{ position.unrealizedPnL > 0 ? '+' : '' }}${{ position.unrealizedPnL.toLocaleString() }}
|
||||||
|
({{ position.unrealizedPnLPercent.toFixed(2) }}%)
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Day Change Column -->
|
||||||
|
<ng-container matColumnDef="dayChange">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Day Change</th>
|
||||||
|
<td mat-cell *matCellDef="let position"
|
||||||
|
class="text-right font-medium"
|
||||||
|
[class]="getPnLColor(position.dayChange)">
|
||||||
|
{{ position.dayChange > 0 ? '+' : '' }}${{ position.dayChange.toFixed(2) }}
|
||||||
|
({{ position.dayChangePercent.toFixed(2) }}%)
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||||
|
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab label="Performance">
|
||||||
|
<div class="p-6">
|
||||||
|
<mat-card class="p-6 h-96 flex items-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem;">trending_up</mat-icon>
|
||||||
|
<p class="mb-4">Performance charts and analytics will be implemented here</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab label="Orders">
|
||||||
|
<div class="p-6">
|
||||||
|
<mat-card class="p-6 h-96 flex items-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem;">receipt</mat-icon>
|
||||||
|
<p class="mb-4">Order history and management will be implemented here</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
</mat-tab-group>
|
||||||
|
</div>
|
||||||
172
apps/dashboard/src/app/pages/portfolio/portfolio.component.ts
Normal file
172
apps/dashboard/src/app/pages/portfolio/portfolio.component.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, inject, OnDestroy, OnInit, signal } from '@angular/core';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||||
|
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||||
|
import { MatTableModule } from '@angular/material/table';
|
||||||
|
import { MatTabsModule } from '@angular/material/tabs';
|
||||||
|
import { interval, Subscription } from 'rxjs';
|
||||||
|
import { ApiService } from '../../services/api.service';
|
||||||
|
|
||||||
|
export interface Position {
|
||||||
|
symbol: string;
|
||||||
|
quantity: number;
|
||||||
|
avgPrice: number;
|
||||||
|
currentPrice: number;
|
||||||
|
marketValue: number;
|
||||||
|
unrealizedPnL: number;
|
||||||
|
unrealizedPnLPercent: number;
|
||||||
|
dayChange: number;
|
||||||
|
dayChangePercent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PortfolioSummary {
|
||||||
|
totalValue: number;
|
||||||
|
totalCost: number;
|
||||||
|
totalPnL: number;
|
||||||
|
totalPnLPercent: number;
|
||||||
|
dayChange: number;
|
||||||
|
dayChangePercent: number;
|
||||||
|
cash: number;
|
||||||
|
positionsCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-portfolio',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
MatCardModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatTableModule,
|
||||||
|
MatProgressSpinnerModule,
|
||||||
|
MatSnackBarModule,
|
||||||
|
MatTabsModule,
|
||||||
|
],
|
||||||
|
templateUrl: './portfolio.component.html',
|
||||||
|
styleUrl: './portfolio.component.css',
|
||||||
|
})
|
||||||
|
export class PortfolioComponent implements OnInit, OnDestroy {
|
||||||
|
private apiService = inject(ApiService);
|
||||||
|
private snackBar = inject(MatSnackBar);
|
||||||
|
private subscriptions: Subscription[] = [];
|
||||||
|
|
||||||
|
protected portfolioSummary = signal<PortfolioSummary>({
|
||||||
|
totalValue: 0,
|
||||||
|
totalCost: 0,
|
||||||
|
totalPnL: 0,
|
||||||
|
totalPnLPercent: 0,
|
||||||
|
dayChange: 0,
|
||||||
|
dayChangePercent: 0,
|
||||||
|
cash: 0,
|
||||||
|
positionsCount: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
protected positions = signal<Position[]>([]);
|
||||||
|
protected isLoading = signal<boolean>(true);
|
||||||
|
protected error = signal<string | null>(null);
|
||||||
|
protected displayedColumns = [
|
||||||
|
'symbol',
|
||||||
|
'quantity',
|
||||||
|
'avgPrice',
|
||||||
|
'currentPrice',
|
||||||
|
'marketValue',
|
||||||
|
'unrealizedPnL',
|
||||||
|
'dayChange',
|
||||||
|
];
|
||||||
|
|
||||||
|
ngOnInit() {
|
||||||
|
this.loadPortfolioData();
|
||||||
|
|
||||||
|
// Refresh portfolio data every 30 seconds
|
||||||
|
const portfolioSubscription = interval(30000).subscribe(() => {
|
||||||
|
this.loadPortfolioData();
|
||||||
|
});
|
||||||
|
this.subscriptions.push(portfolioSubscription);
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy() {
|
||||||
|
this.subscriptions.forEach(sub => sub.unsubscribe());
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadPortfolioData() {
|
||||||
|
// Since we don't have a portfolio endpoint yet, let's create mock data
|
||||||
|
// In a real implementation, this would call this.apiService.getPortfolio()
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
const mockPositions: Position[] = [
|
||||||
|
{
|
||||||
|
symbol: 'AAPL',
|
||||||
|
quantity: 100,
|
||||||
|
avgPrice: 180.5,
|
||||||
|
currentPrice: 192.53,
|
||||||
|
marketValue: 19253,
|
||||||
|
unrealizedPnL: 1203,
|
||||||
|
unrealizedPnLPercent: 6.67,
|
||||||
|
dayChange: 241,
|
||||||
|
dayChangePercent: 1.27,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
symbol: 'MSFT',
|
||||||
|
quantity: 50,
|
||||||
|
avgPrice: 400.0,
|
||||||
|
currentPrice: 415.26,
|
||||||
|
marketValue: 20763,
|
||||||
|
unrealizedPnL: 763,
|
||||||
|
unrealizedPnLPercent: 3.82,
|
||||||
|
dayChange: 436.5,
|
||||||
|
dayChangePercent: 2.15,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
symbol: 'GOOGL',
|
||||||
|
quantity: 10,
|
||||||
|
avgPrice: 2900.0,
|
||||||
|
currentPrice: 2847.56,
|
||||||
|
marketValue: 28475.6,
|
||||||
|
unrealizedPnL: -524.4,
|
||||||
|
unrealizedPnLPercent: -1.81,
|
||||||
|
dayChange: -123.4,
|
||||||
|
dayChangePercent: -0.43,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const summary: PortfolioSummary = {
|
||||||
|
totalValue: mockPositions.reduce((sum, pos) => sum + pos.marketValue, 0) + 25000, // + cash
|
||||||
|
totalCost: mockPositions.reduce((sum, pos) => sum + pos.avgPrice * pos.quantity, 0),
|
||||||
|
totalPnL: mockPositions.reduce((sum, pos) => sum + pos.unrealizedPnL, 0),
|
||||||
|
totalPnLPercent: 0,
|
||||||
|
dayChange: mockPositions.reduce((sum, pos) => sum + pos.dayChange, 0),
|
||||||
|
dayChangePercent: 0,
|
||||||
|
cash: 25000,
|
||||||
|
positionsCount: mockPositions.length,
|
||||||
|
};
|
||||||
|
|
||||||
|
summary.totalPnLPercent = (summary.totalPnL / summary.totalCost) * 100;
|
||||||
|
summary.dayChangePercent =
|
||||||
|
(summary.dayChange / (summary.totalValue - summary.dayChange)) * 100;
|
||||||
|
|
||||||
|
this.positions.set(mockPositions);
|
||||||
|
this.portfolioSummary.set(summary);
|
||||||
|
this.isLoading.set(false);
|
||||||
|
this.error.set(null);
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshData() {
|
||||||
|
this.isLoading.set(true);
|
||||||
|
this.loadPortfolioData();
|
||||||
|
}
|
||||||
|
|
||||||
|
getPnLColor(value: number): string {
|
||||||
|
if (value > 0) {
|
||||||
|
return 'text-green-600';
|
||||||
|
}
|
||||||
|
if (value < 0) {
|
||||||
|
return 'text-red-600';
|
||||||
|
}
|
||||||
|
return 'text-gray-600';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
/* Risk Management specific styles */
|
||||||
|
|
@ -0,0 +1,178 @@
|
||||||
|
<div class="space-y-6">
|
||||||
|
<!-- Page Header -->
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-bold text-gray-900">Risk Management</h1>
|
||||||
|
<p class="text-gray-600 mt-1">Monitor and control trading risks and exposure</p>
|
||||||
|
</div>
|
||||||
|
<button mat-raised-button color="primary" (click)="refreshData()" [disabled]="isLoading()">
|
||||||
|
<mat-icon>refresh</mat-icon>
|
||||||
|
@if (isLoading()) {
|
||||||
|
<mat-spinner diameter="20" class="mr-2"></mat-spinner>
|
||||||
|
}
|
||||||
|
Refresh Data
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Risk Overview Cards -->
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-4 gap-6">
|
||||||
|
@if (riskThresholds(); as thresholds) {
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Max Position Size</p>
|
||||||
|
<p class="text-lg font-semibold text-gray-900">${{ thresholds.maxPositionSize.toLocaleString() }}</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-blue-600 text-3xl">account_balance</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Max Daily Loss</p>
|
||||||
|
<p class="text-lg font-semibold text-red-600">${{ thresholds.maxDailyLoss.toLocaleString() }}</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-red-600 text-3xl">trending_down</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Portfolio Risk Limit</p>
|
||||||
|
<p class="text-lg font-semibold text-yellow-600">{{ (thresholds.maxPortfolioRisk * 100).toFixed(1) }}%</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-yellow-600 text-3xl">pie_chart</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Volatility Limit</p>
|
||||||
|
<p class="text-lg font-semibold text-purple-600">{{ (thresholds.volatilityLimit * 100).toFixed(1) }}%</p>
|
||||||
|
</div>
|
||||||
|
<mat-icon class="text-purple-600 text-3xl">show_chart</mat-icon>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Risk Thresholds Configuration -->
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between mb-4">
|
||||||
|
<h3 class="text-lg font-semibold text-gray-900">Risk Thresholds Configuration</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (isLoading()) {
|
||||||
|
<div class="flex justify-center items-center py-8">
|
||||||
|
<mat-spinner diameter="40"></mat-spinner>
|
||||||
|
<span class="ml-3 text-gray-600">Loading risk settings...</span>
|
||||||
|
</div>
|
||||||
|
} @else if (error()) {
|
||||||
|
<div class="text-center py-8">
|
||||||
|
<mat-icon class="text-red-500 text-4xl">error</mat-icon>
|
||||||
|
<p class="text-red-600 mt-2">{{ error() }}</p>
|
||||||
|
<button mat-button color="primary" (click)="refreshData()" class="mt-2">
|
||||||
|
<mat-icon>refresh</mat-icon>
|
||||||
|
Try Again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<form [formGroup]="thresholdsForm" (ngSubmit)="saveThresholds()">
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<mat-form-field appearance="outline">
|
||||||
|
<mat-label>Max Position Size ($)</mat-label>
|
||||||
|
<input matInput type="number" formControlName="maxPositionSize" placeholder="100000">
|
||||||
|
<mat-icon matSuffix>attach_money</mat-icon>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
<mat-form-field appearance="outline">
|
||||||
|
<mat-label>Max Daily Loss ($)</mat-label>
|
||||||
|
<input matInput type="number" formControlName="maxDailyLoss" placeholder="5000">
|
||||||
|
<mat-icon matSuffix>trending_down</mat-icon>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
<mat-form-field appearance="outline">
|
||||||
|
<mat-label>Max Portfolio Risk (0-1)</mat-label>
|
||||||
|
<input matInput type="number" step="0.01" formControlName="maxPortfolioRisk" placeholder="0.1">
|
||||||
|
<mat-icon matSuffix>pie_chart</mat-icon>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
<mat-form-field appearance="outline">
|
||||||
|
<mat-label>Volatility Limit (0-1)</mat-label>
|
||||||
|
<input matInput type="number" step="0.01" formControlName="volatilityLimit" placeholder="0.3">
|
||||||
|
<mat-icon matSuffix>show_chart</mat-icon>
|
||||||
|
</mat-form-field>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex justify-end mt-4">
|
||||||
|
<button mat-raised-button color="primary" type="submit" [disabled]="thresholdsForm.invalid || isSaving()">
|
||||||
|
@if (isSaving()) {
|
||||||
|
<mat-spinner diameter="20" class="mr-2"></mat-spinner>
|
||||||
|
}
|
||||||
|
Save Thresholds
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<!-- Risk History Table -->
|
||||||
|
<mat-card class="p-6">
|
||||||
|
<div class="flex items-center justify-between mb-4">
|
||||||
|
<h3 class="text-lg font-semibold text-gray-900">Recent Risk Evaluations</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (riskHistory().length === 0) {
|
||||||
|
<div class="text-center py-8 text-gray-500">
|
||||||
|
<mat-icon class="text-4xl">history</mat-icon>
|
||||||
|
<p class="mt-2">No risk evaluations found</p>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table mat-table [dataSource]="riskHistory()" class="mat-elevation-z0 w-full">
|
||||||
|
<!-- Symbol Column -->
|
||||||
|
<ng-container matColumnDef="symbol">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="font-medium text-gray-900">Symbol</th>
|
||||||
|
<td mat-cell *matCellDef="let risk" class="font-semibold text-gray-900">{{ risk.symbol }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Position Value Column -->
|
||||||
|
<ng-container matColumnDef="positionValue">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-right font-medium text-gray-900">Position Value</th>
|
||||||
|
<td mat-cell *matCellDef="let risk" class="text-right font-medium text-gray-900">
|
||||||
|
${{ risk.positionValue.toLocaleString() }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Risk Level Column -->
|
||||||
|
<ng-container matColumnDef="riskLevel">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="text-center font-medium text-gray-900">Risk Level</th>
|
||||||
|
<td mat-cell *matCellDef="let risk" class="text-center">
|
||||||
|
<span class="px-2 py-1 rounded-full text-sm font-medium" [class]="getRiskLevelColor(risk.riskLevel)">
|
||||||
|
{{ risk.riskLevel }}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Violations Column -->
|
||||||
|
<ng-container matColumnDef="violations">
|
||||||
|
<th mat-header-cell *matHeaderCellDef class="font-medium text-gray-900">Violations</th>
|
||||||
|
<td mat-cell *matCellDef="let risk" class="text-gray-600">
|
||||||
|
@if (risk.violations.length > 0) {
|
||||||
|
<span class="text-red-600">{{ risk.violations.join(', ') }}</span>
|
||||||
|
} @else {
|
||||||
|
<span class="text-green-600">None</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||||
|
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
|
@ -0,0 +1,139 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, inject, OnDestroy, OnInit, signal } from '@angular/core';
|
||||||
|
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatInputModule } from '@angular/material/input';
|
||||||
|
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||||
|
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||||
|
import { MatTableModule } from '@angular/material/table';
|
||||||
|
import { interval, Subscription } from 'rxjs';
|
||||||
|
import { ApiService, RiskEvaluation, RiskThresholds } from '../../services/api.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-risk-management',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
MatCardModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatTableModule,
|
||||||
|
MatFormFieldModule,
|
||||||
|
MatInputModule,
|
||||||
|
MatSnackBarModule,
|
||||||
|
MatProgressSpinnerModule,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
],
|
||||||
|
templateUrl: './risk-management.component.html',
|
||||||
|
styleUrl: './risk-management.component.css',
|
||||||
|
})
|
||||||
|
export class RiskManagementComponent implements OnInit, OnDestroy {
|
||||||
|
private apiService = inject(ApiService);
|
||||||
|
private snackBar = inject(MatSnackBar);
|
||||||
|
private fb = inject(FormBuilder);
|
||||||
|
private subscriptions: Subscription[] = [];
|
||||||
|
|
||||||
|
protected riskThresholds = signal<RiskThresholds | null>(null);
|
||||||
|
protected riskHistory = signal<RiskEvaluation[]>([]);
|
||||||
|
protected isLoading = signal<boolean>(true);
|
||||||
|
protected isSaving = signal<boolean>(false);
|
||||||
|
protected error = signal<string | null>(null);
|
||||||
|
|
||||||
|
protected thresholdsForm: FormGroup;
|
||||||
|
protected displayedColumns = ['symbol', 'positionValue', 'riskLevel', 'violations', 'timestamp'];
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.thresholdsForm = this.fb.group({
|
||||||
|
maxPositionSize: [0, [Validators.required, Validators.min(0)]],
|
||||||
|
maxDailyLoss: [0, [Validators.required, Validators.min(0)]],
|
||||||
|
maxPortfolioRisk: [0, [Validators.required, Validators.min(0), Validators.max(1)]],
|
||||||
|
volatilityLimit: [0, [Validators.required, Validators.min(0), Validators.max(1)]],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnInit() {
|
||||||
|
this.loadRiskThresholds();
|
||||||
|
this.loadRiskHistory();
|
||||||
|
|
||||||
|
// Refresh risk history every 30 seconds
|
||||||
|
const historySubscription = interval(30000).subscribe(() => {
|
||||||
|
this.loadRiskHistory();
|
||||||
|
});
|
||||||
|
this.subscriptions.push(historySubscription);
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy() {
|
||||||
|
this.subscriptions.forEach(sub => sub.unsubscribe());
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadRiskThresholds() {
|
||||||
|
this.apiService.getRiskThresholds().subscribe({
|
||||||
|
next: response => {
|
||||||
|
this.riskThresholds.set(response.data);
|
||||||
|
this.thresholdsForm.patchValue(response.data);
|
||||||
|
this.isLoading.set(false);
|
||||||
|
this.error.set(null);
|
||||||
|
},
|
||||||
|
error: err => {
|
||||||
|
console.error('Failed to load risk thresholds:', err);
|
||||||
|
this.error.set('Failed to load risk thresholds');
|
||||||
|
this.isLoading.set(false);
|
||||||
|
this.snackBar.open('Failed to load risk thresholds', 'Dismiss', { duration: 5000 });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadRiskHistory() {
|
||||||
|
this.apiService.getRiskHistory().subscribe({
|
||||||
|
next: response => {
|
||||||
|
this.riskHistory.set(response.data);
|
||||||
|
},
|
||||||
|
error: err => {
|
||||||
|
console.error('Failed to load risk history:', err);
|
||||||
|
this.snackBar.open('Failed to load risk history', 'Dismiss', { duration: 3000 });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
saveThresholds() {
|
||||||
|
if (this.thresholdsForm.valid) {
|
||||||
|
this.isSaving.set(true);
|
||||||
|
const thresholds = this.thresholdsForm.value as RiskThresholds;
|
||||||
|
|
||||||
|
this.apiService.updateRiskThresholds(thresholds).subscribe({
|
||||||
|
next: response => {
|
||||||
|
this.riskThresholds.set(response.data);
|
||||||
|
this.isSaving.set(false);
|
||||||
|
this.snackBar.open('Risk thresholds updated successfully', 'Dismiss', { duration: 3000 });
|
||||||
|
},
|
||||||
|
error: err => {
|
||||||
|
console.error('Failed to save risk thresholds:', err);
|
||||||
|
this.isSaving.set(false);
|
||||||
|
this.snackBar.open('Failed to save risk thresholds', 'Dismiss', { duration: 5000 });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshData() {
|
||||||
|
this.isLoading.set(true);
|
||||||
|
this.loadRiskThresholds();
|
||||||
|
this.loadRiskHistory();
|
||||||
|
}
|
||||||
|
|
||||||
|
getRiskLevelColor(level: string): string {
|
||||||
|
switch (level) {
|
||||||
|
case 'LOW':
|
||||||
|
return 'text-green-600';
|
||||||
|
case 'MEDIUM':
|
||||||
|
return 'text-yellow-600';
|
||||||
|
case 'HIGH':
|
||||||
|
return 'text-red-600';
|
||||||
|
default:
|
||||||
|
return 'text-gray-600';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
/* Settings specific styles */
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
<div class="space-y-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-bold text-gray-900">Settings</h1>
|
||||||
|
<p class="text-gray-600 mt-1">Configure application preferences and system settings</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<mat-card class="p-6 h-96 flex items-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem;">settings</mat-icon>
|
||||||
|
<p class="mb-4">Application settings and configuration will be implemented here</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
13
apps/dashboard/src/app/pages/settings/settings.component.ts
Normal file
13
apps/dashboard/src/app/pages/settings/settings.component.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-settings',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule, MatCardModule, MatIconModule],
|
||||||
|
templateUrl: './settings.component.html',
|
||||||
|
styleUrl: './settings.component.css',
|
||||||
|
})
|
||||||
|
export class SettingsComponent {}
|
||||||
|
|
@ -0,0 +1,167 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
|
||||||
|
import { Chart, ChartOptions } from 'chart.js/auto';
|
||||||
|
import { BacktestResult } from '../../../services/strategy.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-drawdown-chart',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule],
|
||||||
|
template: `
|
||||||
|
<div class="drawdown-chart-container">
|
||||||
|
<canvas #drawdownChart></canvas>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
.drawdown-chart-container {
|
||||||
|
width: 100%;
|
||||||
|
height: 300px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class DrawdownChartComponent implements OnChanges {
|
||||||
|
@Input() backtestResult?: BacktestResult;
|
||||||
|
|
||||||
|
private chart?: Chart;
|
||||||
|
private chartElement?: HTMLCanvasElement;
|
||||||
|
|
||||||
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
|
if (changes['backtestResult'] && this.backtestResult) {
|
||||||
|
this.renderChart();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ngAfterViewInit(): void {
|
||||||
|
this.chartElement = document.querySelector('canvas') as HTMLCanvasElement;
|
||||||
|
if (this.backtestResult) {
|
||||||
|
this.renderChart();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private renderChart(): void {
|
||||||
|
if (!this.chartElement || !this.backtestResult) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up previous chart if it exists
|
||||||
|
if (this.chart) {
|
||||||
|
this.chart.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate drawdown series from daily returns
|
||||||
|
const drawdownData = this.calculateDrawdownSeries(this.backtestResult);
|
||||||
|
|
||||||
|
// Create chart
|
||||||
|
this.chart = new Chart(this.chartElement, {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels: drawdownData.dates.map(date => this.formatDate(date)),
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
label: 'Drawdown',
|
||||||
|
data: drawdownData.drawdowns,
|
||||||
|
borderColor: 'rgba(255, 99, 132, 1)',
|
||||||
|
backgroundColor: 'rgba(255, 99, 132, 0.2)',
|
||||||
|
fill: true,
|
||||||
|
tension: 0.3,
|
||||||
|
borderWidth: 2,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
scales: {
|
||||||
|
x: {
|
||||||
|
ticks: {
|
||||||
|
maxTicksLimit: 12,
|
||||||
|
maxRotation: 0,
|
||||||
|
minRotation: 0,
|
||||||
|
},
|
||||||
|
grid: {
|
||||||
|
display: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
y: {
|
||||||
|
ticks: {
|
||||||
|
callback: function (value) {
|
||||||
|
return (value * 100).toFixed(1) + '%';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
grid: {
|
||||||
|
color: 'rgba(200, 200, 200, 0.2)',
|
||||||
|
},
|
||||||
|
min: -0.05, // Show at least 5% drawdown for context
|
||||||
|
suggestedMax: 0.01,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
tooltip: {
|
||||||
|
mode: 'index',
|
||||||
|
intersect: false,
|
||||||
|
callbacks: {
|
||||||
|
label: function (context) {
|
||||||
|
let label = context.dataset.label || '';
|
||||||
|
if (label) {
|
||||||
|
label += ': ';
|
||||||
|
}
|
||||||
|
if (context.parsed.y !== null) {
|
||||||
|
label += (context.parsed.y * 100).toFixed(2) + '%';
|
||||||
|
}
|
||||||
|
return label;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
legend: {
|
||||||
|
position: 'top',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as ChartOptions,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private calculateDrawdownSeries(result: BacktestResult): {
|
||||||
|
dates: Date[];
|
||||||
|
drawdowns: number[];
|
||||||
|
} {
|
||||||
|
const dates: Date[] = [];
|
||||||
|
const drawdowns: number[] = [];
|
||||||
|
|
||||||
|
// Sort daily returns by date
|
||||||
|
const sortedReturns = [...result.dailyReturns].sort(
|
||||||
|
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()
|
||||||
|
);
|
||||||
|
|
||||||
|
// Calculate equity curve
|
||||||
|
let equity = 1;
|
||||||
|
const equityCurve: number[] = [];
|
||||||
|
|
||||||
|
for (const daily of sortedReturns) {
|
||||||
|
equity *= 1 + daily.return;
|
||||||
|
equityCurve.push(equity);
|
||||||
|
dates.push(new Date(daily.date));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate running maximum (high water mark)
|
||||||
|
let hwm = equityCurve[0];
|
||||||
|
|
||||||
|
for (let i = 0; i < equityCurve.length; i++) {
|
||||||
|
// Update high water mark
|
||||||
|
hwm = Math.max(hwm, equityCurve[i]);
|
||||||
|
// Calculate drawdown as percentage from high water mark
|
||||||
|
const drawdown = equityCurve[i] / hwm - 1;
|
||||||
|
drawdowns.push(drawdown);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { dates, drawdowns };
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return new Date(date).toLocaleDateString('en-US', {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
year: 'numeric',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,175 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
|
||||||
|
import { Chart, ChartOptions } from 'chart.js/auto';
|
||||||
|
import { BacktestResult } from '../../../services/strategy.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-equity-chart',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule],
|
||||||
|
template: `
|
||||||
|
<div class="equity-chart-container">
|
||||||
|
<canvas #equityChart></canvas>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
.equity-chart-container {
|
||||||
|
width: 100%;
|
||||||
|
height: 400px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class EquityChartComponent implements OnChanges {
|
||||||
|
@Input() backtestResult?: BacktestResult;
|
||||||
|
|
||||||
|
private chart?: Chart;
|
||||||
|
private chartElement?: HTMLCanvasElement;
|
||||||
|
|
||||||
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
|
if (changes['backtestResult'] && this.backtestResult) {
|
||||||
|
this.renderChart();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ngAfterViewInit(): void {
|
||||||
|
this.chartElement = document.querySelector('canvas') as HTMLCanvasElement;
|
||||||
|
if (this.backtestResult) {
|
||||||
|
this.renderChart();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private renderChart(): void {
|
||||||
|
if (!this.chartElement || !this.backtestResult) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up previous chart if it exists
|
||||||
|
if (this.chart) {
|
||||||
|
this.chart.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare data
|
||||||
|
const equityCurve = this.calculateEquityCurve(this.backtestResult);
|
||||||
|
|
||||||
|
// Create chart
|
||||||
|
this.chart = new Chart(this.chartElement, {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels: equityCurve.dates.map(date => this.formatDate(date)),
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
label: 'Portfolio Value',
|
||||||
|
data: equityCurve.values,
|
||||||
|
borderColor: 'rgba(75, 192, 192, 1)',
|
||||||
|
backgroundColor: 'rgba(75, 192, 192, 0.2)',
|
||||||
|
tension: 0.3,
|
||||||
|
borderWidth: 2,
|
||||||
|
fill: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Benchmark',
|
||||||
|
data: equityCurve.benchmark,
|
||||||
|
borderColor: 'rgba(153, 102, 255, 0.5)',
|
||||||
|
backgroundColor: 'rgba(153, 102, 255, 0.1)',
|
||||||
|
borderDash: [5, 5],
|
||||||
|
tension: 0.3,
|
||||||
|
borderWidth: 1,
|
||||||
|
fill: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
scales: {
|
||||||
|
x: {
|
||||||
|
ticks: {
|
||||||
|
maxTicksLimit: 12,
|
||||||
|
maxRotation: 0,
|
||||||
|
minRotation: 0,
|
||||||
|
},
|
||||||
|
grid: {
|
||||||
|
display: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
y: {
|
||||||
|
ticks: {
|
||||||
|
callback: function (value) {
|
||||||
|
return '$' + value.toLocaleString();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
grid: {
|
||||||
|
color: 'rgba(200, 200, 200, 0.2)',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
tooltip: {
|
||||||
|
mode: 'index',
|
||||||
|
intersect: false,
|
||||||
|
callbacks: {
|
||||||
|
label: function (context) {
|
||||||
|
let label = context.dataset.label || '';
|
||||||
|
if (label) {
|
||||||
|
label += ': ';
|
||||||
|
}
|
||||||
|
if (context.parsed.y !== null) {
|
||||||
|
label += new Intl.NumberFormat('en-US', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'USD',
|
||||||
|
}).format(context.parsed.y);
|
||||||
|
}
|
||||||
|
return label;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
legend: {
|
||||||
|
position: 'top',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as ChartOptions,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private calculateEquityCurve(result: BacktestResult): {
|
||||||
|
dates: Date[];
|
||||||
|
values: number[];
|
||||||
|
benchmark: number[];
|
||||||
|
} {
|
||||||
|
const initialValue = result.initialCapital;
|
||||||
|
const dates: Date[] = [];
|
||||||
|
const values: number[] = [];
|
||||||
|
const benchmark: number[] = [];
|
||||||
|
|
||||||
|
// Sort daily returns by date
|
||||||
|
const sortedReturns = [...result.dailyReturns].sort(
|
||||||
|
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()
|
||||||
|
);
|
||||||
|
|
||||||
|
// Calculate cumulative portfolio values
|
||||||
|
let portfolioValue = initialValue;
|
||||||
|
let benchmarkValue = initialValue;
|
||||||
|
|
||||||
|
for (const daily of sortedReturns) {
|
||||||
|
const date = new Date(daily.date);
|
||||||
|
portfolioValue = portfolioValue * (1 + daily.return);
|
||||||
|
// Simple benchmark (e.g., assuming 8% annualized return for a market index)
|
||||||
|
benchmarkValue = benchmarkValue * (1 + 0.08 / 365);
|
||||||
|
|
||||||
|
dates.push(date);
|
||||||
|
values.push(portfolioValue);
|
||||||
|
benchmark.push(benchmarkValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { dates, values, benchmark };
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return new Date(date).toLocaleDateString('en-US', {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
year: 'numeric',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,322 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, Input } from '@angular/core';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatDividerModule } from '@angular/material/divider';
|
||||||
|
import { MatGridListModule } from '@angular/material/grid-list';
|
||||||
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
|
import { BacktestResult } from '../../../services/strategy.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-performance-metrics',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule, MatCardModule, MatGridListModule, MatDividerModule, MatTooltipModule],
|
||||||
|
template: `
|
||||||
|
<mat-card class="metrics-card">
|
||||||
|
<mat-card-header>
|
||||||
|
<mat-card-title>Performance Metrics</mat-card-title>
|
||||||
|
</mat-card-header>
|
||||||
|
<mat-card-content>
|
||||||
|
<div class="metrics-grid">
|
||||||
|
<div class="metric-group">
|
||||||
|
<h3>Returns</h3>
|
||||||
|
<div class="metrics-row">
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Total return over the backtest period">
|
||||||
|
Total Return
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="metric-value"
|
||||||
|
[ngClass]="getReturnClass(backtestResult?.totalReturn || 0)"
|
||||||
|
>
|
||||||
|
{{ formatPercent(backtestResult?.totalReturn || 0) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div
|
||||||
|
class="metric-name"
|
||||||
|
matTooltip="Annualized return (adjusted for the backtest duration)"
|
||||||
|
>
|
||||||
|
Annualized Return
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="metric-value"
|
||||||
|
[ngClass]="getReturnClass(backtestResult?.annualizedReturn || 0)"
|
||||||
|
>
|
||||||
|
{{ formatPercent(backtestResult?.annualizedReturn || 0) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Compound Annual Growth Rate">CAGR</div>
|
||||||
|
<div class="metric-value" [ngClass]="getReturnClass(backtestResult?.cagr || 0)">
|
||||||
|
{{ formatPercent(backtestResult?.cagr || 0) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<mat-divider></mat-divider>
|
||||||
|
|
||||||
|
<div class="metric-group">
|
||||||
|
<h3>Risk Metrics</h3>
|
||||||
|
<div class="metrics-row">
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Maximum peak-to-valley drawdown">
|
||||||
|
Max Drawdown
|
||||||
|
</div>
|
||||||
|
<div class="metric-value negative">
|
||||||
|
{{ formatPercent(backtestResult?.maxDrawdown || 0) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Number of days in the worst drawdown">
|
||||||
|
Max DD Duration
|
||||||
|
</div>
|
||||||
|
<div class="metric-value">
|
||||||
|
{{ formatDays(backtestResult?.maxDrawdownDuration || 0) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Annualized standard deviation of returns">
|
||||||
|
Volatility
|
||||||
|
</div>
|
||||||
|
<div class="metric-value">
|
||||||
|
{{ formatPercent(backtestResult?.volatility || 0) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div
|
||||||
|
class="metric-name"
|
||||||
|
matTooltip="Square root of the sum of the squares of drawdowns"
|
||||||
|
>
|
||||||
|
Ulcer Index
|
||||||
|
</div>
|
||||||
|
<div class="metric-value">
|
||||||
|
{{ (backtestResult?.ulcerIndex || 0).toFixed(4) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<mat-divider></mat-divider>
|
||||||
|
|
||||||
|
<div class="metric-group">
|
||||||
|
<h3>Risk-Adjusted Returns</h3>
|
||||||
|
<div class="metrics-row">
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Excess return per unit of risk">
|
||||||
|
Sharpe Ratio
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="metric-value"
|
||||||
|
[ngClass]="getRatioClass(backtestResult?.sharpeRatio || 0)"
|
||||||
|
>
|
||||||
|
{{ (backtestResult?.sharpeRatio || 0).toFixed(2) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Return per unit of downside risk">
|
||||||
|
Sortino Ratio
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="metric-value"
|
||||||
|
[ngClass]="getRatioClass(backtestResult?.sortinoRatio || 0)"
|
||||||
|
>
|
||||||
|
{{ (backtestResult?.sortinoRatio || 0).toFixed(2) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Return per unit of max drawdown">
|
||||||
|
Calmar Ratio
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="metric-value"
|
||||||
|
[ngClass]="getRatioClass(backtestResult?.calmarRatio || 0)"
|
||||||
|
>
|
||||||
|
{{ (backtestResult?.calmarRatio || 0).toFixed(2) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div
|
||||||
|
class="metric-name"
|
||||||
|
matTooltip="Probability-weighted ratio of gains vs. losses"
|
||||||
|
>
|
||||||
|
Omega Ratio
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="metric-value"
|
||||||
|
[ngClass]="getRatioClass(backtestResult?.omegaRatio || 0)"
|
||||||
|
>
|
||||||
|
{{ (backtestResult?.omegaRatio || 0).toFixed(2) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<mat-divider></mat-divider>
|
||||||
|
|
||||||
|
<div class="metric-group">
|
||||||
|
<h3>Trade Statistics</h3>
|
||||||
|
<div class="metrics-row">
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Total number of trades">Total Trades</div>
|
||||||
|
<div class="metric-value">
|
||||||
|
{{ backtestResult?.totalTrades || 0 }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Percentage of winning trades">Win Rate</div>
|
||||||
|
<div class="metric-value" [ngClass]="getWinRateClass(backtestResult?.winRate || 0)">
|
||||||
|
{{ formatPercent(backtestResult?.winRate || 0) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Average profit of winning trades">Avg Win</div>
|
||||||
|
<div class="metric-value positive">
|
||||||
|
{{ formatPercent(backtestResult?.averageWinningTrade || 0) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Average loss of losing trades">Avg Loss</div>
|
||||||
|
<div class="metric-value negative">
|
||||||
|
{{ formatPercent(backtestResult?.averageLosingTrade || 0) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<div class="metric-name" matTooltip="Ratio of total gains to total losses">
|
||||||
|
Profit Factor
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="metric-value"
|
||||||
|
[ngClass]="getProfitFactorClass(backtestResult?.profitFactor || 0)"
|
||||||
|
>
|
||||||
|
{{ (backtestResult?.profitFactor || 0).toFixed(2) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
.metrics-card {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics-grid {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-group {
|
||||||
|
padding: 10px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-group h3 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics-row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric {
|
||||||
|
min-width: 120px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-name {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #666;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-value {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.positive {
|
||||||
|
color: #4caf50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.negative {
|
||||||
|
color: #f44336;
|
||||||
|
}
|
||||||
|
|
||||||
|
.neutral {
|
||||||
|
color: #ffa000;
|
||||||
|
}
|
||||||
|
|
||||||
|
mat-divider {
|
||||||
|
margin: 8px 0;
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class PerformanceMetricsComponent {
|
||||||
|
@Input() backtestResult?: BacktestResult;
|
||||||
|
|
||||||
|
// Formatting helpers
|
||||||
|
formatPercent(value: number): string {
|
||||||
|
return new Intl.NumberFormat('en-US', {
|
||||||
|
style: 'percent',
|
||||||
|
minimumFractionDigits: 2,
|
||||||
|
maximumFractionDigits: 2,
|
||||||
|
}).format(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
formatDays(days: number): string {
|
||||||
|
return `${days} days`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conditional classes
|
||||||
|
getReturnClass(value: number): string {
|
||||||
|
if (value > 0) {
|
||||||
|
return 'positive';
|
||||||
|
}
|
||||||
|
if (value < 0) {
|
||||||
|
return 'negative';
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
getRatioClass(value: number): string {
|
||||||
|
if (value >= 1.5) {
|
||||||
|
return 'positive';
|
||||||
|
}
|
||||||
|
if (value >= 1) {
|
||||||
|
return 'neutral';
|
||||||
|
}
|
||||||
|
if (value < 0) {
|
||||||
|
return 'negative';
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
getWinRateClass(value: number): string {
|
||||||
|
if (value >= 0.55) {
|
||||||
|
return 'positive';
|
||||||
|
}
|
||||||
|
if (value >= 0.45) {
|
||||||
|
return 'neutral';
|
||||||
|
}
|
||||||
|
return 'negative';
|
||||||
|
}
|
||||||
|
|
||||||
|
getProfitFactorClass(value: number): string {
|
||||||
|
if (value >= 1.5) {
|
||||||
|
return 'positive';
|
||||||
|
}
|
||||||
|
if (value >= 1) {
|
||||||
|
return 'neutral';
|
||||||
|
}
|
||||||
|
return 'negative';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,259 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, Input } from '@angular/core';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
|
||||||
|
import { MatSortModule, Sort } from '@angular/material/sort';
|
||||||
|
import { MatTableModule } from '@angular/material/table';
|
||||||
|
import { BacktestResult } from '../../../services/strategy.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-trades-table',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
MatTableModule,
|
||||||
|
MatSortModule,
|
||||||
|
MatPaginatorModule,
|
||||||
|
MatCardModule,
|
||||||
|
MatIconModule,
|
||||||
|
],
|
||||||
|
template: `
|
||||||
|
<mat-card class="trades-card">
|
||||||
|
<mat-card-header>
|
||||||
|
<mat-card-title>Trades</mat-card-title>
|
||||||
|
</mat-card-header>
|
||||||
|
<mat-card-content>
|
||||||
|
<table
|
||||||
|
mat-table
|
||||||
|
[dataSource]="displayedTrades"
|
||||||
|
matSort
|
||||||
|
(matSortChange)="sortData($event)"
|
||||||
|
class="trades-table"
|
||||||
|
>
|
||||||
|
<!-- Symbol Column -->
|
||||||
|
<ng-container matColumnDef="symbol">
|
||||||
|
<th mat-header-cell *matHeaderCellDef mat-sort-header>Symbol</th>
|
||||||
|
<td mat-cell *matCellDef="let trade">{{ trade.symbol }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Entry Date Column -->
|
||||||
|
<ng-container matColumnDef="entryTime">
|
||||||
|
<th mat-header-cell *matHeaderCellDef mat-sort-header>Entry Time</th>
|
||||||
|
<td mat-cell *matCellDef="let trade">{{ formatDate(trade.entryTime) }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Entry Price Column -->
|
||||||
|
<ng-container matColumnDef="entryPrice">
|
||||||
|
<th mat-header-cell *matHeaderCellDef mat-sort-header>Entry Price</th>
|
||||||
|
<td mat-cell *matCellDef="let trade">{{ formatCurrency(trade.entryPrice) }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Exit Date Column -->
|
||||||
|
<ng-container matColumnDef="exitTime">
|
||||||
|
<th mat-header-cell *matHeaderCellDef mat-sort-header>Exit Time</th>
|
||||||
|
<td mat-cell *matCellDef="let trade">{{ formatDate(trade.exitTime) }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Exit Price Column -->
|
||||||
|
<ng-container matColumnDef="exitPrice">
|
||||||
|
<th mat-header-cell *matHeaderCellDef mat-sort-header>Exit Price</th>
|
||||||
|
<td mat-cell *matCellDef="let trade">{{ formatCurrency(trade.exitPrice) }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Quantity Column -->
|
||||||
|
<ng-container matColumnDef="quantity">
|
||||||
|
<th mat-header-cell *matHeaderCellDef mat-sort-header>Quantity</th>
|
||||||
|
<td mat-cell *matCellDef="let trade">{{ trade.quantity }}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- P&L Column -->
|
||||||
|
<ng-container matColumnDef="pnl">
|
||||||
|
<th mat-header-cell *matHeaderCellDef mat-sort-header>P&L</th>
|
||||||
|
<td
|
||||||
|
mat-cell
|
||||||
|
*matCellDef="let trade"
|
||||||
|
[ngClass]="{ positive: trade.pnl > 0, negative: trade.pnl < 0 }"
|
||||||
|
>
|
||||||
|
{{ formatCurrency(trade.pnl) }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- P&L Percent Column -->
|
||||||
|
<ng-container matColumnDef="pnlPercent">
|
||||||
|
<th mat-header-cell *matHeaderCellDef mat-sort-header>P&L %</th>
|
||||||
|
<td
|
||||||
|
mat-cell
|
||||||
|
*matCellDef="let trade"
|
||||||
|
[ngClass]="{ positive: trade.pnlPercent > 0, negative: trade.pnlPercent < 0 }"
|
||||||
|
>
|
||||||
|
{{ formatPercent(trade.pnlPercent) }}
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||||
|
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<mat-paginator
|
||||||
|
[length]="totalTrades"
|
||||||
|
[pageSize]="pageSize"
|
||||||
|
[pageSizeOptions]="[5, 10, 25, 50]"
|
||||||
|
(page)="pageChange($event)"
|
||||||
|
aria-label="Select page"
|
||||||
|
>
|
||||||
|
</mat-paginator>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
.trades-card {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trades-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-column-pnl,
|
||||||
|
.mat-column-pnlPercent {
|
||||||
|
text-align: right;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.positive {
|
||||||
|
color: #4caf50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.negative {
|
||||||
|
color: #f44336;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-row:hover {
|
||||||
|
background-color: rgba(0, 0, 0, 0.04);
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class TradesTableComponent {
|
||||||
|
@Input() set backtestResult(value: BacktestResult | undefined) {
|
||||||
|
if (value) {
|
||||||
|
this._backtestResult = value;
|
||||||
|
this.updateDisplayedTrades();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
get backtestResult(): BacktestResult | undefined {
|
||||||
|
return this._backtestResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _backtestResult?: BacktestResult;
|
||||||
|
|
||||||
|
// Table configuration
|
||||||
|
displayedColumns: string[] = [
|
||||||
|
'symbol',
|
||||||
|
'entryTime',
|
||||||
|
'entryPrice',
|
||||||
|
'exitTime',
|
||||||
|
'exitPrice',
|
||||||
|
'quantity',
|
||||||
|
'pnl',
|
||||||
|
'pnlPercent',
|
||||||
|
];
|
||||||
|
|
||||||
|
// Pagination
|
||||||
|
pageSize = 10;
|
||||||
|
currentPage = 0;
|
||||||
|
displayedTrades: any[] = [];
|
||||||
|
|
||||||
|
get totalTrades(): number {
|
||||||
|
return this._backtestResult?.trades.length || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort the trades
|
||||||
|
sortData(sort: Sort): void {
|
||||||
|
if (!sort.active || sort.direction === '') {
|
||||||
|
this.updateDisplayedTrades();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = this._backtestResult?.trades.slice() || [];
|
||||||
|
|
||||||
|
this.displayedTrades = data
|
||||||
|
.sort((a, b) => {
|
||||||
|
const isAsc = sort.direction === 'asc';
|
||||||
|
switch (sort.active) {
|
||||||
|
case 'symbol':
|
||||||
|
return this.compare(a.symbol, b.symbol, isAsc);
|
||||||
|
case 'entryTime':
|
||||||
|
return this.compare(
|
||||||
|
new Date(a.entryTime).getTime(),
|
||||||
|
new Date(b.entryTime).getTime(),
|
||||||
|
isAsc
|
||||||
|
);
|
||||||
|
case 'entryPrice':
|
||||||
|
return this.compare(a.entryPrice, b.entryPrice, isAsc);
|
||||||
|
case 'exitTime':
|
||||||
|
return this.compare(
|
||||||
|
new Date(a.exitTime).getTime(),
|
||||||
|
new Date(b.exitTime).getTime(),
|
||||||
|
isAsc
|
||||||
|
);
|
||||||
|
case 'exitPrice':
|
||||||
|
return this.compare(a.exitPrice, b.exitPrice, isAsc);
|
||||||
|
case 'quantity':
|
||||||
|
return this.compare(a.quantity, b.quantity, isAsc);
|
||||||
|
case 'pnl':
|
||||||
|
return this.compare(a.pnl, b.pnl, isAsc);
|
||||||
|
case 'pnlPercent':
|
||||||
|
return this.compare(a.pnlPercent, b.pnlPercent, isAsc);
|
||||||
|
default:
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.slice(this.currentPage * this.pageSize, (this.currentPage + 1) * this.pageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle page changes
|
||||||
|
pageChange(event: PageEvent): void {
|
||||||
|
this.pageSize = event.pageSize;
|
||||||
|
this.currentPage = event.pageIndex;
|
||||||
|
this.updateDisplayedTrades();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update displayed trades based on current page and page size
|
||||||
|
updateDisplayedTrades(): void {
|
||||||
|
if (this._backtestResult) {
|
||||||
|
this.displayedTrades = this._backtestResult.trades.slice(
|
||||||
|
this.currentPage * this.pageSize,
|
||||||
|
(this.currentPage + 1) * this.pageSize
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
this.displayedTrades = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper methods for formatting
|
||||||
|
formatDate(date: Date | string): string {
|
||||||
|
return new Date(date).toLocaleString();
|
||||||
|
}
|
||||||
|
|
||||||
|
formatCurrency(value: number): string {
|
||||||
|
return new Intl.NumberFormat('en-US', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'USD',
|
||||||
|
}).format(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
formatPercent(value: number): string {
|
||||||
|
return new Intl.NumberFormat('en-US', {
|
||||||
|
style: 'percent',
|
||||||
|
minimumFractionDigits: 2,
|
||||||
|
maximumFractionDigits: 2,
|
||||||
|
}).format(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private compare(a: number | string, b: number | string, isAsc: boolean): number {
|
||||||
|
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,195 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, Inject, OnInit } from '@angular/core';
|
||||||
|
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatChipsModule } from '@angular/material/chips';
|
||||||
|
import { MatNativeDateModule } from '@angular/material/core';
|
||||||
|
import { MatDatepickerModule } from '@angular/material/datepicker';
|
||||||
|
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||||
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatInputModule } from '@angular/material/input';
|
||||||
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
|
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
|
||||||
|
import { MatTabsModule } from '@angular/material/tabs';
|
||||||
|
import {
|
||||||
|
BacktestRequest,
|
||||||
|
BacktestResult,
|
||||||
|
StrategyService,
|
||||||
|
TradingStrategy,
|
||||||
|
} from '../../../services/strategy.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-backtest-dialog',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatDialogModule,
|
||||||
|
MatFormFieldModule,
|
||||||
|
MatInputModule,
|
||||||
|
MatSelectModule,
|
||||||
|
MatDatepickerModule,
|
||||||
|
MatNativeDateModule,
|
||||||
|
MatProgressBarModule,
|
||||||
|
MatTabsModule,
|
||||||
|
MatChipsModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatSlideToggleModule,
|
||||||
|
],
|
||||||
|
templateUrl: './backtest-dialog.component.html',
|
||||||
|
styleUrl: './backtest-dialog.component.css',
|
||||||
|
})
|
||||||
|
export class BacktestDialogComponent implements OnInit {
|
||||||
|
backtestForm: FormGroup;
|
||||||
|
strategyTypes: string[] = [];
|
||||||
|
availableSymbols: string[] = [
|
||||||
|
'AAPL',
|
||||||
|
'MSFT',
|
||||||
|
'GOOGL',
|
||||||
|
'AMZN',
|
||||||
|
'TSLA',
|
||||||
|
'META',
|
||||||
|
'NVDA',
|
||||||
|
'SPY',
|
||||||
|
'QQQ',
|
||||||
|
];
|
||||||
|
selectedSymbols: string[] = [];
|
||||||
|
parameters: Record<string, any> = {};
|
||||||
|
isRunning: boolean = false;
|
||||||
|
backtestResult: BacktestResult | null = null;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private fb: FormBuilder,
|
||||||
|
private strategyService: StrategyService,
|
||||||
|
@Inject(MAT_DIALOG_DATA) public data: TradingStrategy | null,
|
||||||
|
private dialogRef: MatDialogRef<BacktestDialogComponent>
|
||||||
|
) {
|
||||||
|
// Initialize form with defaults
|
||||||
|
this.backtestForm = this.fb.group({
|
||||||
|
strategyType: ['', [Validators.required]],
|
||||||
|
startDate: [
|
||||||
|
new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
|
||||||
|
[Validators.required],
|
||||||
|
],
|
||||||
|
endDate: [new Date(), [Validators.required]],
|
||||||
|
initialCapital: [100000, [Validators.required, Validators.min(1000)]],
|
||||||
|
dataResolution: ['1d', [Validators.required]],
|
||||||
|
commission: [0.001, [Validators.required, Validators.min(0), Validators.max(0.1)]],
|
||||||
|
slippage: [0.0005, [Validators.required, Validators.min(0), Validators.max(0.1)]],
|
||||||
|
mode: ['event', [Validators.required]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// If strategy is provided, pre-populate the form
|
||||||
|
if (data) {
|
||||||
|
this.selectedSymbols = [...data.symbols];
|
||||||
|
this.backtestForm.patchValue({
|
||||||
|
strategyType: data.type,
|
||||||
|
});
|
||||||
|
this.parameters = { ...data.parameters };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.loadStrategyTypes();
|
||||||
|
}
|
||||||
|
|
||||||
|
loadStrategyTypes(): void {
|
||||||
|
this.strategyService.getStrategyTypes().subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
this.strategyTypes = response.data;
|
||||||
|
|
||||||
|
// If strategy is provided, load its parameters
|
||||||
|
if (this.data) {
|
||||||
|
this.onStrategyTypeChange(this.data.type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error loading strategy types:', error);
|
||||||
|
this.strategyTypes = ['MOVING_AVERAGE_CROSSOVER', 'MEAN_REVERSION', 'CUSTOM'];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onStrategyTypeChange(type: string): void {
|
||||||
|
// Get default parameters for this strategy type
|
||||||
|
this.strategyService.getStrategyParameters(type).subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
// If strategy is provided, merge default with existing
|
||||||
|
if (this.data) {
|
||||||
|
this.parameters = {
|
||||||
|
...response.data,
|
||||||
|
...this.data.parameters,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
this.parameters = response.data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error loading parameters:', error);
|
||||||
|
this.parameters = {};
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
addSymbol(symbol: string): void {
|
||||||
|
if (!symbol || this.selectedSymbols.includes(symbol)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.selectedSymbols.push(symbol);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeSymbol(symbol: string): void {
|
||||||
|
this.selectedSymbols = this.selectedSymbols.filter(s => s !== symbol);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateParameter(key: string, value: any): void {
|
||||||
|
this.parameters[key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubmit(): void {
|
||||||
|
if (this.backtestForm.invalid || this.selectedSymbols.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const formValue = this.backtestForm.value;
|
||||||
|
|
||||||
|
const backtestRequest: BacktestRequest = {
|
||||||
|
strategyType: formValue.strategyType,
|
||||||
|
strategyParams: this.parameters,
|
||||||
|
symbols: this.selectedSymbols,
|
||||||
|
startDate: formValue.startDate,
|
||||||
|
endDate: formValue.endDate,
|
||||||
|
initialCapital: formValue.initialCapital,
|
||||||
|
dataResolution: formValue.dataResolution,
|
||||||
|
commission: formValue.commission,
|
||||||
|
slippage: formValue.slippage,
|
||||||
|
mode: formValue.mode,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.isRunning = true;
|
||||||
|
|
||||||
|
this.strategyService.runBacktest(backtestRequest).subscribe({
|
||||||
|
next: response => {
|
||||||
|
this.isRunning = false;
|
||||||
|
if (response.success) {
|
||||||
|
this.backtestResult = response.data;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
this.isRunning = false;
|
||||||
|
console.error('Backtest error:', error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
this.dialogRef.close(this.backtestResult);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,84 @@
|
||||||
|
<h2 mat-dialog-title>{{isEditMode ? 'Edit Strategy' : 'Create Strategy'}}</h2>
|
||||||
|
|
||||||
|
<form [formGroup]="strategyForm" (ngSubmit)="onSubmit()">
|
||||||
|
<mat-dialog-content class="mat-typography">
|
||||||
|
<div class="grid grid-cols-1 gap-4">
|
||||||
|
<!-- Basic Strategy Information -->
|
||||||
|
<mat-form-field appearance="outline" class="w-full">
|
||||||
|
<mat-label>Strategy Name</mat-label>
|
||||||
|
<input matInput formControlName="name" placeholder="e.g., My Moving Average Crossover">
|
||||||
|
<mat-error *ngIf="strategyForm.get('name')?.invalid">Name is required</mat-error>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
<mat-form-field appearance="outline" class="w-full">
|
||||||
|
<mat-label>Description</mat-label>
|
||||||
|
<textarea matInput formControlName="description" rows="3"
|
||||||
|
placeholder="Describe what this strategy does..."></textarea>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
<mat-form-field appearance="outline" class="w-full">
|
||||||
|
<mat-label>Strategy Type</mat-label>
|
||||||
|
<mat-select formControlName="type" (selectionChange)="onStrategyTypeChange($event.value)">
|
||||||
|
<mat-option *ngFor="let type of strategyTypes" [value]="type">
|
||||||
|
{{type}}
|
||||||
|
</mat-option>
|
||||||
|
</mat-select>
|
||||||
|
<mat-error *ngIf="strategyForm.get('type')?.invalid">Strategy type is required</mat-error>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
<!-- Symbol Selection -->
|
||||||
|
<div class="w-full">
|
||||||
|
<label class="text-sm">Trading Symbols</label>
|
||||||
|
<div class="flex flex-wrap gap-2 mb-2">
|
||||||
|
<mat-chip *ngFor="let symbol of selectedSymbols" [removable]="true"
|
||||||
|
(removed)="removeSymbol(symbol)">
|
||||||
|
{{symbol}}
|
||||||
|
<mat-icon matChipRemove>cancel</mat-icon>
|
||||||
|
</mat-chip>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<mat-form-field appearance="outline" class="flex-1">
|
||||||
|
<mat-label>Add Symbol</mat-label>
|
||||||
|
<input matInput #symbolInput placeholder="e.g., AAPL">
|
||||||
|
</mat-form-field>
|
||||||
|
<button type="button" mat-raised-button color="primary"
|
||||||
|
(click)="addSymbol(symbolInput.value); symbolInput.value = ''">
|
||||||
|
Add
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-2">
|
||||||
|
<p class="text-sm text-gray-500 mb-1">Suggested symbols:</p>
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
<button type="button" *ngFor="let symbol of availableSymbols"
|
||||||
|
mat-stroked-button (click)="addSymbol(symbol)"
|
||||||
|
[disabled]="selectedSymbols.includes(symbol)">
|
||||||
|
{{symbol}}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Dynamic Strategy Parameters -->
|
||||||
|
<div *ngIf="strategyForm.get('type')?.value && Object.keys(parameters).length > 0">
|
||||||
|
<h3 class="text-lg font-semibold mb-2">Strategy Parameters</h3>
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<mat-form-field *ngFor="let param of parameters | keyvalue" appearance="outline">
|
||||||
|
<mat-label>{{param.key}}</mat-label>
|
||||||
|
<input matInput [value]="param.value"
|
||||||
|
(input)="updateParameter(param.key, $any($event.target).value)">
|
||||||
|
</mat-form-field>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</mat-dialog-content>
|
||||||
|
|
||||||
|
<mat-dialog-actions align="end">
|
||||||
|
<button mat-button mat-dialog-close>Cancel</button>
|
||||||
|
<button mat-raised-button color="primary" type="submit"
|
||||||
|
[disabled]="strategyForm.invalid || selectedSymbols.length === 0">
|
||||||
|
{{isEditMode ? 'Update' : 'Create'}}
|
||||||
|
</button>
|
||||||
|
</mat-dialog-actions>
|
||||||
|
</form>
|
||||||
|
|
@ -0,0 +1,182 @@
|
||||||
|
import { COMMA, ENTER } from '@angular/cdk/keycodes';
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, Inject, OnInit } from '@angular/core';
|
||||||
|
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
|
import { MatAutocompleteModule } from '@angular/material/autocomplete';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatChipsModule } from '@angular/material/chips';
|
||||||
|
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||||
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatInputModule } from '@angular/material/input';
|
||||||
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
|
import { StrategyService, TradingStrategy } from '../../../services/strategy.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-strategy-dialog',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatDialogModule,
|
||||||
|
MatFormFieldModule,
|
||||||
|
MatInputModule,
|
||||||
|
MatSelectModule,
|
||||||
|
MatChipsModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatAutocompleteModule,
|
||||||
|
],
|
||||||
|
templateUrl: './strategy-dialog.component.html',
|
||||||
|
styleUrl: './strategy-dialog.component.css',
|
||||||
|
})
|
||||||
|
export class StrategyDialogComponent implements OnInit {
|
||||||
|
strategyForm: FormGroup;
|
||||||
|
isEditMode: boolean = false;
|
||||||
|
strategyTypes: string[] = [];
|
||||||
|
availableSymbols: string[] = [
|
||||||
|
'AAPL',
|
||||||
|
'MSFT',
|
||||||
|
'GOOGL',
|
||||||
|
'AMZN',
|
||||||
|
'TSLA',
|
||||||
|
'META',
|
||||||
|
'NVDA',
|
||||||
|
'SPY',
|
||||||
|
'QQQ',
|
||||||
|
];
|
||||||
|
selectedSymbols: string[] = [];
|
||||||
|
separatorKeysCodes: number[] = [ENTER, COMMA];
|
||||||
|
parameters: Record<string, any> = {};
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private fb: FormBuilder,
|
||||||
|
private strategyService: StrategyService,
|
||||||
|
@Inject(MAT_DIALOG_DATA) public data: TradingStrategy | null,
|
||||||
|
private dialogRef: MatDialogRef<StrategyDialogComponent>
|
||||||
|
) {
|
||||||
|
this.isEditMode = !!data;
|
||||||
|
|
||||||
|
this.strategyForm = this.fb.group({
|
||||||
|
name: ['', [Validators.required]],
|
||||||
|
description: [''],
|
||||||
|
type: ['', [Validators.required]],
|
||||||
|
// Dynamic parameters will be added based on strategy type
|
||||||
|
});
|
||||||
|
|
||||||
|
if (this.isEditMode && data) {
|
||||||
|
this.selectedSymbols = [...data.symbols];
|
||||||
|
this.strategyForm.patchValue({
|
||||||
|
name: data.name,
|
||||||
|
description: data.description,
|
||||||
|
type: data.type,
|
||||||
|
});
|
||||||
|
this.parameters = { ...data.parameters };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
// In a real implementation, fetch available strategy types from the API
|
||||||
|
this.loadStrategyTypes();
|
||||||
|
}
|
||||||
|
|
||||||
|
loadStrategyTypes(): void {
|
||||||
|
// In a real implementation, this would call the API
|
||||||
|
this.strategyService.getStrategyTypes().subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
this.strategyTypes = response.data;
|
||||||
|
|
||||||
|
// If editing, load parameters
|
||||||
|
if (this.isEditMode && this.data) {
|
||||||
|
this.onStrategyTypeChange(this.data.type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error loading strategy types:', error);
|
||||||
|
// Fallback to hardcoded types
|
||||||
|
this.strategyTypes = ['MOVING_AVERAGE_CROSSOVER', 'MEAN_REVERSION', 'CUSTOM'];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onStrategyTypeChange(type: string): void {
|
||||||
|
// Get default parameters for this strategy type
|
||||||
|
this.strategyService.getStrategyParameters(type).subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
// If editing, merge default with existing
|
||||||
|
if (this.isEditMode && this.data) {
|
||||||
|
this.parameters = {
|
||||||
|
...response.data,
|
||||||
|
...this.data.parameters,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
this.parameters = response.data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error loading parameters:', error);
|
||||||
|
// Fallback to empty parameters
|
||||||
|
this.parameters = {};
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
addSymbol(symbol: string): void {
|
||||||
|
if (!symbol || this.selectedSymbols.includes(symbol)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.selectedSymbols.push(symbol);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeSymbol(symbol: string): void {
|
||||||
|
this.selectedSymbols = this.selectedSymbols.filter(s => s !== symbol);
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubmit(): void {
|
||||||
|
if (this.strategyForm.invalid || this.selectedSymbols.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const formValue = this.strategyForm.value;
|
||||||
|
|
||||||
|
const strategy: Partial<TradingStrategy> = {
|
||||||
|
name: formValue.name,
|
||||||
|
description: formValue.description,
|
||||||
|
type: formValue.type,
|
||||||
|
symbols: this.selectedSymbols,
|
||||||
|
parameters: this.parameters,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (this.isEditMode && this.data) {
|
||||||
|
this.strategyService.updateStrategy(this.data.id, strategy).subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
this.dialogRef.close(true);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error updating strategy:', error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.strategyService.createStrategy(strategy).subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
this.dialogRef.close(true);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error creating strategy:', error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
updateParameter(key: string, value: any): void {
|
||||||
|
this.parameters[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
/* Strategies specific styles */
|
||||||
|
|
@ -0,0 +1,142 @@
|
||||||
|
<div class="space-y-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-bold text-gray-900">Trading Strategies</h1>
|
||||||
|
<p class="text-gray-600 mt-1">Configure and monitor your automated trading strategies</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button mat-raised-button color="primary" (click)="openStrategyDialog()">
|
||||||
|
<mat-icon>add</mat-icon> New Strategy
|
||||||
|
</button>
|
||||||
|
<button mat-raised-button color="accent" (click)="openBacktestDialog()">
|
||||||
|
<mat-icon>science</mat-icon> New Backtest
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<mat-card *ngIf="isLoading" class="p-4">
|
||||||
|
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<div *ngIf="!selectedStrategy; else strategyDetails">
|
||||||
|
<mat-card *ngIf="strategies.length > 0; else noStrategies" class="p-4">
|
||||||
|
<table mat-table [dataSource]="strategies" class="w-full">
|
||||||
|
<!-- Name Column -->
|
||||||
|
<ng-container matColumnDef="name">
|
||||||
|
<th mat-header-cell *matHeaderCellDef>Strategy</th>
|
||||||
|
<td mat-cell *matCellDef="let strategy">
|
||||||
|
<div class="font-semibold">{{strategy.name}}</div>
|
||||||
|
<div class="text-xs text-gray-500">{{strategy.description}}</div>
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Type Column -->
|
||||||
|
<ng-container matColumnDef="type">
|
||||||
|
<th mat-header-cell *matHeaderCellDef>Type</th>
|
||||||
|
<td mat-cell *matCellDef="let strategy">{{strategy.type}}</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Symbols Column -->
|
||||||
|
<ng-container matColumnDef="symbols">
|
||||||
|
<th mat-header-cell *matHeaderCellDef>Symbols</th>
|
||||||
|
<td mat-cell *matCellDef="let strategy">
|
||||||
|
<div class="flex flex-wrap gap-1 max-w-xs">
|
||||||
|
<mat-chip *ngFor="let symbol of strategy.symbols.slice(0, 3)">
|
||||||
|
{{symbol}}
|
||||||
|
</mat-chip>
|
||||||
|
<span *ngIf="strategy.symbols.length > 3" class="text-gray-500">
|
||||||
|
+{{strategy.symbols.length - 3}} more
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Status Column -->
|
||||||
|
<ng-container matColumnDef="status">
|
||||||
|
<th mat-header-cell *matHeaderCellDef>Status</th>
|
||||||
|
<td mat-cell *matCellDef="let strategy">
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<span class="w-2 h-2 rounded-full"
|
||||||
|
[style.background-color]="getStatusColor(strategy.status)"></span>
|
||||||
|
{{strategy.status}}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Performance Column -->
|
||||||
|
<ng-container matColumnDef="performance">
|
||||||
|
<th mat-header-cell *matHeaderCellDef>Performance</th>
|
||||||
|
<td mat-cell *matCellDef="let strategy">
|
||||||
|
<div class="flex flex-col">
|
||||||
|
<div class="flex justify-between">
|
||||||
|
<span class="text-xs text-gray-500">Return:</span>
|
||||||
|
<span [ngClass]="{'text-green-600': strategy.performance.totalReturn > 0,
|
||||||
|
'text-red-600': strategy.performance.totalReturn < 0}">
|
||||||
|
{{strategy.performance.totalReturn | percent:'1.2-2'}}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex justify-between">
|
||||||
|
<span class="text-xs text-gray-500">Win Rate:</span>
|
||||||
|
<span>{{strategy.performance.winRate | percent:'1.0-0'}}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- Actions Column -->
|
||||||
|
<ng-container matColumnDef="actions">
|
||||||
|
<th mat-header-cell *matHeaderCellDef>Actions</th>
|
||||||
|
<td mat-cell *matCellDef="let strategy">
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button mat-icon-button color="primary" (click)="viewStrategyDetails(strategy)">
|
||||||
|
<mat-icon>visibility</mat-icon>
|
||||||
|
</button>
|
||||||
|
<button mat-icon-button [color]="strategy.status === 'ACTIVE' ? 'warn' : 'primary'"
|
||||||
|
(click)="toggleStrategyStatus(strategy)">
|
||||||
|
<mat-icon>{{strategy.status === 'ACTIVE' ? 'pause' : 'play_arrow'}}</mat-icon>
|
||||||
|
</button>
|
||||||
|
<button mat-icon-button [matMenuTriggerFor]="menu">
|
||||||
|
<mat-icon>more_vert</mat-icon>
|
||||||
|
</button>
|
||||||
|
<mat-menu #menu="matMenu">
|
||||||
|
<button mat-menu-item (click)="openStrategyDialog(strategy)">
|
||||||
|
<mat-icon>edit</mat-icon>
|
||||||
|
<span>Edit</span>
|
||||||
|
</button>
|
||||||
|
<button mat-menu-item (click)="openBacktestDialog(strategy)">
|
||||||
|
<mat-icon>science</mat-icon>
|
||||||
|
<span>Backtest</span>
|
||||||
|
</button>
|
||||||
|
</mat-menu>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||||
|
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
|
||||||
|
</table>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<ng-template #noStrategies>
|
||||||
|
<mat-card class="p-6 flex flex-col items-center justify-center">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem; margin: 0 auto;">psychology</mat-icon>
|
||||||
|
<h3 class="text-xl font-semibold mt-4">No Strategies Yet</h3>
|
||||||
|
<p class="mb-4">Create your first trading strategy to get started</p>
|
||||||
|
<button mat-raised-button color="primary" (click)="openStrategyDialog()">
|
||||||
|
<mat-icon>add</mat-icon> Create Strategy
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</ng-template>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ng-template #strategyDetails>
|
||||||
|
<div class="flex justify-between items-center mb-4">
|
||||||
|
<button mat-button (click)="selectedStrategy = null">
|
||||||
|
<mat-icon>arrow_back</mat-icon> Back to Strategies
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<app-strategy-details [strategy]="selectedStrategy"></app-strategy-details>
|
||||||
|
</ng-template>
|
||||||
|
</div>
|
||||||
154
apps/dashboard/src/app/pages/strategies/strategies.component.ts
Normal file
154
apps/dashboard/src/app/pages/strategies/strategies.component.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, OnInit } from '@angular/core';
|
||||||
|
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatChipsModule } from '@angular/material/chips';
|
||||||
|
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatMenuModule } from '@angular/material/menu';
|
||||||
|
import { MatPaginatorModule } from '@angular/material/paginator';
|
||||||
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
|
import { MatSortModule } from '@angular/material/sort';
|
||||||
|
import { MatTableModule } from '@angular/material/table';
|
||||||
|
import { MatTabsModule } from '@angular/material/tabs';
|
||||||
|
import { StrategyService, TradingStrategy } from '../../services/strategy.service';
|
||||||
|
import { WebSocketService } from '../../services/websocket.service';
|
||||||
|
import { BacktestDialogComponent } from './dialogs/backtest-dialog.component';
|
||||||
|
import { StrategyDialogComponent } from './dialogs/strategy-dialog.component';
|
||||||
|
import { StrategyDetailsComponent } from './strategy-details/strategy-details.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-strategies',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
MatCardModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatTabsModule,
|
||||||
|
MatTableModule,
|
||||||
|
MatSortModule,
|
||||||
|
MatPaginatorModule,
|
||||||
|
MatDialogModule,
|
||||||
|
MatMenuModule,
|
||||||
|
MatChipsModule,
|
||||||
|
MatProgressBarModule,
|
||||||
|
FormsModule,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
StrategyDetailsComponent,
|
||||||
|
],
|
||||||
|
templateUrl: './strategies.component.html',
|
||||||
|
styleUrl: './strategies.component.css',
|
||||||
|
})
|
||||||
|
export class StrategiesComponent implements OnInit {
|
||||||
|
strategies: TradingStrategy[] = [];
|
||||||
|
displayedColumns: string[] = ['name', 'type', 'symbols', 'status', 'performance', 'actions'];
|
||||||
|
selectedStrategy: TradingStrategy | null = null;
|
||||||
|
isLoading = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private strategyService: StrategyService,
|
||||||
|
private webSocketService: WebSocketService,
|
||||||
|
private dialog: MatDialog
|
||||||
|
) {}
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.loadStrategies();
|
||||||
|
this.listenForStrategyUpdates();
|
||||||
|
}
|
||||||
|
|
||||||
|
loadStrategies(): void {
|
||||||
|
this.isLoading = true;
|
||||||
|
this.strategyService.getStrategies().subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
this.strategies = response.data;
|
||||||
|
}
|
||||||
|
this.isLoading = false;
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error loading strategies:', error);
|
||||||
|
this.isLoading = false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
listenForStrategyUpdates(): void {
|
||||||
|
this.webSocketService.messages.subscribe(message => {
|
||||||
|
if (
|
||||||
|
message.type === 'STRATEGY_CREATED' ||
|
||||||
|
message.type === 'STRATEGY_UPDATED' ||
|
||||||
|
message.type === 'STRATEGY_STATUS_CHANGED'
|
||||||
|
) {
|
||||||
|
// Refresh the strategy list when changes occur
|
||||||
|
this.loadStrategies();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
getStatusColor(status: string): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'ACTIVE':
|
||||||
|
return 'green';
|
||||||
|
case 'PAUSED':
|
||||||
|
return 'orange';
|
||||||
|
case 'ERROR':
|
||||||
|
return 'red';
|
||||||
|
default:
|
||||||
|
return 'gray';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
openStrategyDialog(strategy?: TradingStrategy): void {
|
||||||
|
const dialogRef = this.dialog.open(StrategyDialogComponent, {
|
||||||
|
width: '600px',
|
||||||
|
data: strategy || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
dialogRef.afterClosed().subscribe(result => {
|
||||||
|
if (result) {
|
||||||
|
this.loadStrategies();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
openBacktestDialog(strategy?: TradingStrategy): void {
|
||||||
|
const dialogRef = this.dialog.open(BacktestDialogComponent, {
|
||||||
|
width: '800px',
|
||||||
|
data: strategy || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
dialogRef.afterClosed().subscribe(result => {
|
||||||
|
if (result) {
|
||||||
|
// Handle backtest result if needed
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
toggleStrategyStatus(strategy: TradingStrategy): void {
|
||||||
|
this.isLoading = true;
|
||||||
|
|
||||||
|
if (strategy.status === 'ACTIVE') {
|
||||||
|
this.strategyService.pauseStrategy(strategy.id).subscribe({
|
||||||
|
next: () => this.loadStrategies(),
|
||||||
|
error: error => {
|
||||||
|
console.error('Error pausing strategy:', error);
|
||||||
|
this.isLoading = false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.strategyService.startStrategy(strategy.id).subscribe({
|
||||||
|
next: () => this.loadStrategies(),
|
||||||
|
error: error => {
|
||||||
|
console.error('Error starting strategy:', error);
|
||||||
|
this.isLoading = false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
viewStrategyDetails(strategy: TradingStrategy): void {
|
||||||
|
this.selectedStrategy = strategy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
/* Strategy details specific styles */
|
||||||
|
table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
font-weight: 600;
|
||||||
|
color: #4b5563;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
border-bottom: 1px solid #e5e7eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
td {
|
||||||
|
border-bottom: 1px solid #e5e7eb;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,249 @@
|
||||||
|
<div class="space-y-6" *ngIf="strategy">
|
||||||
|
<div class="flex flex-col md:flex-row md:justify-between md:items-start gap-4">
|
||||||
|
<!-- Strategy Overview Card -->
|
||||||
|
<mat-card class="flex-1 p-4">
|
||||||
|
<div class="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 class="text-xl font-bold">{{ strategy.name }}</h2>
|
||||||
|
<p class="text-gray-600 text-sm">{{ strategy.description }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<button mat-raised-button color="primary" class="mr-2" (click)="openBacktestDialog()">
|
||||||
|
Run Backtest
|
||||||
|
</button>
|
||||||
|
<span
|
||||||
|
class="px-3 py-1 rounded-full text-xs font-semibold"
|
||||||
|
[style.background-color]="getStatusColor(strategy.status)"
|
||||||
|
style="color: white"
|
||||||
|
>
|
||||||
|
{{ strategy.status }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<h3 class="font-semibold text-sm text-gray-600">Type</h3>
|
||||||
|
<p>{{ strategy.type }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 class="font-semibold text-sm text-gray-600">Created</h3>
|
||||||
|
<p>{{ strategy.createdAt | date: 'medium' }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 class="font-semibold text-sm text-gray-600">Last Updated</h3>
|
||||||
|
<p>{{ strategy.updatedAt | date: 'medium' }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 class="font-semibold text-sm text-gray-600">Symbols</h3>
|
||||||
|
<div class="flex flex-wrap gap-1 mt-1">
|
||||||
|
<mat-chip *ngFor="let symbol of strategy.symbols">{{ symbol }}</mat-chip>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<!-- Performance Summary Card -->
|
||||||
|
<mat-card class="md:w-1/3 p-4">
|
||||||
|
<h3 class="text-lg font-bold mb-3">Performance</h3>
|
||||||
|
<div class="grid grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Return</p>
|
||||||
|
<p
|
||||||
|
class="text-xl font-semibold"
|
||||||
|
[ngClass]="{
|
||||||
|
'text-green-600': performance.totalReturn >= 0,
|
||||||
|
'text-red-600': performance.totalReturn < 0,
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
{{ performance.totalReturn | percent: '1.2-2' }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Win Rate</p>
|
||||||
|
<p class="text-xl font-semibold">{{ performance.winRate | percent: '1.0-0' }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Sharpe Ratio</p>
|
||||||
|
<p class="text-xl font-semibold">{{ performance.sharpeRatio | number: '1.2-2' }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Max Drawdown</p>
|
||||||
|
<p class="text-xl font-semibold text-red-600">
|
||||||
|
{{ performance.maxDrawdown | percent: '1.2-2' }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Total Trades</p>
|
||||||
|
<p class="text-xl font-semibold">{{ performance.totalTrades }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-600">Sortino Ratio</p>
|
||||||
|
<p class="text-xl font-semibold">{{ performance.sortinoRatio | number: '1.2-2' }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<mat-divider class="my-4"></mat-divider>
|
||||||
|
|
||||||
|
<div class="flex justify-between mt-2">
|
||||||
|
<button
|
||||||
|
mat-button
|
||||||
|
color="primary"
|
||||||
|
*ngIf="strategy.status !== 'ACTIVE'"
|
||||||
|
(click)="activateStrategy()"
|
||||||
|
>
|
||||||
|
<mat-icon>play_arrow</mat-icon> Start
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
mat-button
|
||||||
|
color="accent"
|
||||||
|
*ngIf="strategy.status === 'ACTIVE'"
|
||||||
|
(click)="pauseStrategy()"
|
||||||
|
>
|
||||||
|
<mat-icon>pause</mat-icon> Pause
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
mat-button
|
||||||
|
color="warn"
|
||||||
|
*ngIf="strategy.status === 'ACTIVE'"
|
||||||
|
(click)="stopStrategy()"
|
||||||
|
>
|
||||||
|
<mat-icon>stop</mat-icon> Stop
|
||||||
|
</button>
|
||||||
|
<button mat-button (click)="openEditDialog()"><mat-icon>edit</mat-icon> Edit</button>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Parameters Card -->
|
||||||
|
<mat-card class="p-4">
|
||||||
|
<h3 class="text-lg font-bold mb-3">Strategy Parameters</h3>
|
||||||
|
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||||
|
<div *ngFor="let param of strategy.parameters | keyvalue">
|
||||||
|
<p class="text-sm text-gray-600">{{ param.key }}</p>
|
||||||
|
<p class="font-semibold">{{ param.value }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
<!-- Backtest Results Section (only shown when a backtest has been run) -->
|
||||||
|
<div *ngIf="backtestResult" class="backtest-results space-y-6">
|
||||||
|
<h2 class="text-xl font-bold">Backtest Results</h2>
|
||||||
|
|
||||||
|
<!-- Performance Metrics Component -->
|
||||||
|
<app-performance-metrics [backtestResult]="backtestResult"></app-performance-metrics>
|
||||||
|
|
||||||
|
<!-- Equity Chart Component -->
|
||||||
|
<app-equity-chart [backtestResult]="backtestResult"></app-equity-chart>
|
||||||
|
|
||||||
|
<!-- Drawdown Chart Component -->
|
||||||
|
<app-drawdown-chart [backtestResult]="backtestResult"></app-drawdown-chart>
|
||||||
|
|
||||||
|
<!-- Trades Table Component -->
|
||||||
|
<app-trades-table [backtestResult]="backtestResult"></app-trades-table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tabs for Signals/Trades -->
|
||||||
|
<mat-card class="p-0">
|
||||||
|
<mat-tab-group>
|
||||||
|
<!-- Signals Tab -->
|
||||||
|
<mat-tab label="Recent Signals">
|
||||||
|
<div class="p-4">
|
||||||
|
<ng-container *ngIf="!isLoadingSignals; else loadingSignals">
|
||||||
|
<table class="min-w-full">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="py-2 text-left">Time</th>
|
||||||
|
<th class="py-2 text-left">Symbol</th>
|
||||||
|
<th class="py-2 text-left">Action</th>
|
||||||
|
<th class="py-2 text-left">Price</th>
|
||||||
|
<th class="py-2 text-left">Quantity</th>
|
||||||
|
<th class="py-2 text-left">Confidence</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr *ngFor="let signal of signals">
|
||||||
|
<td class="py-2">{{ signal.timestamp | date: 'short' }}</td>
|
||||||
|
<td class="py-2">{{ signal.symbol }}</td>
|
||||||
|
<td class="py-2">
|
||||||
|
<span
|
||||||
|
class="px-2 py-1 rounded text-xs font-semibold"
|
||||||
|
[style.background-color]="getSignalColor(signal.action)"
|
||||||
|
style="color: white"
|
||||||
|
>
|
||||||
|
{{ signal.action }}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td class="py-2">${{ signal.price | number: '1.2-2' }}</td>
|
||||||
|
<td class="py-2">{{ signal.quantity }}</td>
|
||||||
|
<td class="py-2">{{ signal.confidence | percent: '1.0-0' }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</ng-container>
|
||||||
|
<ng-template #loadingSignals>
|
||||||
|
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
|
||||||
|
</ng-template>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<!-- Trades Tab -->
|
||||||
|
<mat-tab label="Recent Trades">
|
||||||
|
<div class="p-4">
|
||||||
|
<ng-container *ngIf="!isLoadingTrades; else loadingTrades">
|
||||||
|
<table class="min-w-full">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="py-2 text-left">Symbol</th>
|
||||||
|
<th class="py-2 text-left">Entry</th>
|
||||||
|
<th class="py-2 text-left">Exit</th>
|
||||||
|
<th class="py-2 text-left">Quantity</th>
|
||||||
|
<th class="py-2 text-left">P&L</th>
|
||||||
|
<th class="py-2 text-left">P&L %</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr *ngFor="let trade of trades">
|
||||||
|
<td class="py-2">{{ trade.symbol }}</td>
|
||||||
|
<td class="py-2">
|
||||||
|
${{ trade.entryPrice | number: '1.2-2' }} @
|
||||||
|
{{ trade.entryTime | date: 'short' }}
|
||||||
|
</td>
|
||||||
|
<td class="py-2">
|
||||||
|
${{ trade.exitPrice | number: '1.2-2' }} @
|
||||||
|
{{ trade.exitTime | date: 'short' }}
|
||||||
|
</td>
|
||||||
|
<td class="py-2">{{ trade.quantity }}</td>
|
||||||
|
<td
|
||||||
|
class="py-2"
|
||||||
|
[ngClass]="{ 'text-green-600': trade.pnl >= 0, 'text-red-600': trade.pnl < 0 }"
|
||||||
|
>
|
||||||
|
${{ trade.pnl | number: '1.2-2' }}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
class="py-2"
|
||||||
|
[ngClass]="{
|
||||||
|
'text-green-600': trade.pnlPercent >= 0,
|
||||||
|
'text-red-600': trade.pnlPercent < 0,
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
{{ trade.pnlPercent | number: '1.2-2' }}%
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</ng-container>
|
||||||
|
<ng-template #loadingTrades>
|
||||||
|
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
|
||||||
|
</ng-template>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
</mat-tab-group>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<mat-card class="p-6 flex items-center" *ngIf="!strategy">
|
||||||
|
<div class="text-center text-gray-500 w-full">
|
||||||
|
<mat-icon style="font-size: 4rem; width: 4rem; height: 4rem">psychology</mat-icon>
|
||||||
|
<p class="mb-4">No strategy selected</p>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
|
@ -0,0 +1,415 @@
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatChipsModule } from '@angular/material/chips';
|
||||||
|
import { MatDialog } from '@angular/material/dialog';
|
||||||
|
import { MatDividerModule } from '@angular/material/divider';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
|
import { MatTableModule } from '@angular/material/table';
|
||||||
|
import { MatTabsModule } from '@angular/material/tabs';
|
||||||
|
import {
|
||||||
|
BacktestResult,
|
||||||
|
StrategyService,
|
||||||
|
TradingStrategy,
|
||||||
|
} from '../../../services/strategy.service';
|
||||||
|
import { WebSocketService } from '../../../services/websocket.service';
|
||||||
|
import { DrawdownChartComponent } from '../components/drawdown-chart.component';
|
||||||
|
import { EquityChartComponent } from '../components/equity-chart.component';
|
||||||
|
import { PerformanceMetricsComponent } from '../components/performance-metrics.component';
|
||||||
|
import { TradesTableComponent } from '../components/trades-table.component';
|
||||||
|
import { BacktestDialogComponent } from '../dialogs/backtest-dialog.component';
|
||||||
|
import { StrategyDialogComponent } from '../dialogs/strategy-dialog.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-strategy-details',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
MatCardModule,
|
||||||
|
MatTabsModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatTableModule,
|
||||||
|
MatChipsModule,
|
||||||
|
MatProgressBarModule,
|
||||||
|
MatDividerModule,
|
||||||
|
EquityChartComponent,
|
||||||
|
DrawdownChartComponent,
|
||||||
|
TradesTableComponent,
|
||||||
|
PerformanceMetricsComponent,
|
||||||
|
],
|
||||||
|
templateUrl: './strategy-details.component.html',
|
||||||
|
styleUrl: './strategy-details.component.css',
|
||||||
|
})
|
||||||
|
export class StrategyDetailsComponent implements OnChanges {
|
||||||
|
@Input() strategy: TradingStrategy | null = null;
|
||||||
|
|
||||||
|
signals: any[] = [];
|
||||||
|
trades: any[] = [];
|
||||||
|
performance: any = {};
|
||||||
|
isLoadingSignals = false;
|
||||||
|
isLoadingTrades = false;
|
||||||
|
backtestResult: BacktestResult | undefined;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private strategyService: StrategyService,
|
||||||
|
private webSocketService: WebSocketService,
|
||||||
|
private dialog: MatDialog
|
||||||
|
) {}
|
||||||
|
|
||||||
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
|
if (changes['strategy'] && this.strategy) {
|
||||||
|
this.loadStrategyData();
|
||||||
|
this.listenForUpdates();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadStrategyData(): void {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// In a real implementation, these would call API methods to fetch the data
|
||||||
|
this.loadSignals();
|
||||||
|
this.loadTrades();
|
||||||
|
this.loadPerformance();
|
||||||
|
}
|
||||||
|
loadSignals(): void {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isLoadingSignals = true;
|
||||||
|
|
||||||
|
// First check if we can get real signals from the API
|
||||||
|
this.strategyService.getStrategySignals(this.strategy.id).subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success && response.data && response.data.length > 0) {
|
||||||
|
this.signals = response.data;
|
||||||
|
} else {
|
||||||
|
// Fallback to mock data if no real signals available
|
||||||
|
this.signals = this.generateMockSignals();
|
||||||
|
}
|
||||||
|
this.isLoadingSignals = false;
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error loading signals', error);
|
||||||
|
// Fallback to mock data on error
|
||||||
|
this.signals = this.generateMockSignals();
|
||||||
|
this.isLoadingSignals = false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
loadTrades(): void {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isLoadingTrades = true;
|
||||||
|
|
||||||
|
// First check if we can get real trades from the API
|
||||||
|
this.strategyService.getStrategyTrades(this.strategy.id).subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success && response.data && response.data.length > 0) {
|
||||||
|
this.trades = response.data;
|
||||||
|
} else {
|
||||||
|
// Fallback to mock data if no real trades available
|
||||||
|
this.trades = this.generateMockTrades();
|
||||||
|
}
|
||||||
|
this.isLoadingTrades = false;
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error loading trades', error);
|
||||||
|
// Fallback to mock data on error
|
||||||
|
this.trades = this.generateMockTrades();
|
||||||
|
this.isLoadingTrades = false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
loadPerformance(): void {
|
||||||
|
// This would be an API call in a real implementation
|
||||||
|
this.performance = {
|
||||||
|
totalReturn: this.strategy?.performance.totalReturn || 0,
|
||||||
|
winRate: this.strategy?.performance.winRate || 0,
|
||||||
|
sharpeRatio: this.strategy?.performance.sharpeRatio || 0,
|
||||||
|
maxDrawdown: this.strategy?.performance.maxDrawdown || 0,
|
||||||
|
totalTrades: this.strategy?.performance.totalTrades || 0,
|
||||||
|
// Additional metrics that would come from the API
|
||||||
|
dailyReturn: 0.0012,
|
||||||
|
volatility: 0.008,
|
||||||
|
sortinoRatio: 1.2,
|
||||||
|
calmarRatio: 0.7,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
listenForUpdates(): void {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subscribe to strategy signals
|
||||||
|
this.webSocketService.getStrategySignals(this.strategy.id).subscribe((signal: any) => {
|
||||||
|
// Add the new signal to the top of the list
|
||||||
|
this.signals = [signal, ...this.signals.slice(0, 9)]; // Keep only the latest 10 signals
|
||||||
|
});
|
||||||
|
|
||||||
|
// Subscribe to strategy trades
|
||||||
|
this.webSocketService.getStrategyTrades(this.strategy.id).subscribe((trade: any) => {
|
||||||
|
// Add the new trade to the top of the list
|
||||||
|
this.trades = [trade, ...this.trades.slice(0, 9)]; // Keep only the latest 10 trades
|
||||||
|
|
||||||
|
// Update performance metrics
|
||||||
|
this.updatePerformanceMetrics();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Subscribe to strategy status updates
|
||||||
|
this.webSocketService.getStrategyUpdates().subscribe((update: any) => {
|
||||||
|
if (update.strategyId === this.strategy?.id) {
|
||||||
|
// Update strategy status if changed
|
||||||
|
if (update.status && this.strategy && this.strategy.status !== update.status) {
|
||||||
|
this.strategy.status = update.status;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update other fields if present
|
||||||
|
if (update.performance && this.strategy) {
|
||||||
|
this.strategy.performance = {
|
||||||
|
...this.strategy.performance,
|
||||||
|
...update.performance,
|
||||||
|
};
|
||||||
|
this.performance = {
|
||||||
|
...this.performance,
|
||||||
|
...update.performance,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('WebSocket listeners for strategy updates initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update performance metrics when new trades come in
|
||||||
|
*/
|
||||||
|
private updatePerformanceMetrics(): void {
|
||||||
|
if (!this.strategy || this.trades.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate basic metrics
|
||||||
|
const winningTrades = this.trades.filter(t => t.pnl > 0);
|
||||||
|
const losingTrades = this.trades.filter(t => t.pnl < 0);
|
||||||
|
|
||||||
|
const totalPnl = this.trades.reduce((sum, trade) => sum + trade.pnl, 0);
|
||||||
|
const winRate = winningTrades.length / this.trades.length;
|
||||||
|
|
||||||
|
// Update performance data
|
||||||
|
const currentPerformance = this.performance || {};
|
||||||
|
this.performance = {
|
||||||
|
...currentPerformance,
|
||||||
|
totalTrades: this.trades.length,
|
||||||
|
winRate: winRate,
|
||||||
|
winningTrades,
|
||||||
|
losingTrades,
|
||||||
|
totalReturn: (currentPerformance.totalReturn || 0) + totalPnl / 10000, // Approximate
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update strategy performance as well
|
||||||
|
if (this.strategy && this.strategy.performance) {
|
||||||
|
this.strategy.performance = {
|
||||||
|
...this.strategy.performance,
|
||||||
|
totalTrades: this.trades.length,
|
||||||
|
winRate: winRate,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getStatusColor(status: string): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'ACTIVE':
|
||||||
|
return 'green';
|
||||||
|
case 'PAUSED':
|
||||||
|
return 'orange';
|
||||||
|
case 'ERROR':
|
||||||
|
return 'red';
|
||||||
|
default:
|
||||||
|
return 'gray';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getSignalColor(action: string): string {
|
||||||
|
switch (action) {
|
||||||
|
case 'BUY':
|
||||||
|
return 'green';
|
||||||
|
case 'SELL':
|
||||||
|
return 'red';
|
||||||
|
default:
|
||||||
|
return 'gray';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open the backtest dialog to run a backtest for this strategy
|
||||||
|
*/
|
||||||
|
openBacktestDialog(): void {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dialogRef = this.dialog.open(BacktestDialogComponent, {
|
||||||
|
width: '800px',
|
||||||
|
data: this.strategy,
|
||||||
|
});
|
||||||
|
|
||||||
|
dialogRef.afterClosed().subscribe(result => {
|
||||||
|
if (result) {
|
||||||
|
// Store the backtest result for visualization
|
||||||
|
this.backtestResult = result;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open the strategy edit dialog
|
||||||
|
*/
|
||||||
|
openEditDialog(): void {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dialogRef = this.dialog.open(StrategyDialogComponent, {
|
||||||
|
width: '600px',
|
||||||
|
data: this.strategy,
|
||||||
|
});
|
||||||
|
|
||||||
|
dialogRef.afterClosed().subscribe(result => {
|
||||||
|
if (result) {
|
||||||
|
// Refresh strategy data after edit
|
||||||
|
this.loadStrategyData();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start the strategy
|
||||||
|
*/
|
||||||
|
activateStrategy(): void {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.strategyService.startStrategy(this.strategy.id).subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
this.strategy!.status = 'ACTIVE';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error starting strategy:', error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pause the strategy
|
||||||
|
*/
|
||||||
|
pauseStrategy(): void {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.strategyService.pauseStrategy(this.strategy.id).subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
this.strategy!.status = 'PAUSED';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error pausing strategy:', error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop the strategy
|
||||||
|
*/
|
||||||
|
stopStrategy(): void {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.strategyService.stopStrategy(this.strategy.id).subscribe({
|
||||||
|
next: response => {
|
||||||
|
if (response.success) {
|
||||||
|
this.strategy!.status = 'INACTIVE';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: error => {
|
||||||
|
console.error('Error stopping strategy:', error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Methods to generate mock data
|
||||||
|
private generateMockSignals(): any[] {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const signals = [];
|
||||||
|
const actions = ['BUY', 'SELL', 'HOLD'];
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
const symbol =
|
||||||
|
this.strategy.symbols[Math.floor(Math.random() * this.strategy.symbols.length)];
|
||||||
|
const action = actions[Math.floor(Math.random() * actions.length)];
|
||||||
|
|
||||||
|
signals.push({
|
||||||
|
id: `sig_${i}`,
|
||||||
|
symbol,
|
||||||
|
action,
|
||||||
|
confidence: 0.7 + Math.random() * 0.3,
|
||||||
|
price: 100 + Math.random() * 50,
|
||||||
|
timestamp: new Date(now.getTime() - i * 1000 * 60 * 30), // 30 min intervals
|
||||||
|
quantity: Math.floor(10 + Math.random() * 90),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return signals;
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateMockTrades(): any[] {
|
||||||
|
if (!this.strategy) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const trades = [];
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
const symbol =
|
||||||
|
this.strategy.symbols[Math.floor(Math.random() * this.strategy.symbols.length)];
|
||||||
|
const entryPrice = 100 + Math.random() * 50;
|
||||||
|
const exitPrice = entryPrice * (1 + (Math.random() * 0.1 - 0.05)); // -5% to +5%
|
||||||
|
const quantity = Math.floor(10 + Math.random() * 90);
|
||||||
|
const pnl = (exitPrice - entryPrice) * quantity;
|
||||||
|
|
||||||
|
trades.push({
|
||||||
|
id: `trade_${i}`,
|
||||||
|
symbol,
|
||||||
|
entryPrice,
|
||||||
|
entryTime: new Date(now.getTime() - (i + 5) * 1000 * 60 * 60), // Hourly intervals
|
||||||
|
exitPrice,
|
||||||
|
exitTime: new Date(now.getTime() - i * 1000 * 60 * 60),
|
||||||
|
quantity,
|
||||||
|
pnl,
|
||||||
|
pnlPercent: ((exitPrice - entryPrice) / entryPrice) * 100,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return trades;
|
||||||
|
}
|
||||||
|
}
|
||||||
104
apps/dashboard/src/app/services/api.service.ts
Normal file
104
apps/dashboard/src/app/services/api.service.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
||||||
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
export interface RiskThresholds {
|
||||||
|
maxPositionSize: number;
|
||||||
|
maxDailyLoss: number;
|
||||||
|
maxPortfolioRisk: number;
|
||||||
|
volatilityLimit: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiskEvaluation {
|
||||||
|
symbol: string;
|
||||||
|
positionValue: number;
|
||||||
|
positionRisk: number;
|
||||||
|
violations: string[];
|
||||||
|
riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MarketData {
|
||||||
|
symbol: string;
|
||||||
|
price: number;
|
||||||
|
change: number;
|
||||||
|
changePercent: number;
|
||||||
|
volume: number;
|
||||||
|
timestamp: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class ApiService {
|
||||||
|
private readonly baseUrls = {
|
||||||
|
riskGuardian: 'http://localhost:3002',
|
||||||
|
strategyOrchestrator: 'http://localhost:3003',
|
||||||
|
marketDataGateway: 'http://localhost:3001',
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor(private http: HttpClient) {}
|
||||||
|
|
||||||
|
// Risk Guardian API
|
||||||
|
getRiskThresholds(): Observable<{ success: boolean; data: RiskThresholds }> {
|
||||||
|
return this.http.get<{ success: boolean; data: RiskThresholds }>(
|
||||||
|
`${this.baseUrls.riskGuardian}/api/risk/thresholds`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateRiskThresholds(
|
||||||
|
thresholds: RiskThresholds
|
||||||
|
): Observable<{ success: boolean; data: RiskThresholds }> {
|
||||||
|
return this.http.put<{ success: boolean; data: RiskThresholds }>(
|
||||||
|
`${this.baseUrls.riskGuardian}/api/risk/thresholds`,
|
||||||
|
thresholds
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
evaluateRisk(params: {
|
||||||
|
symbol: string;
|
||||||
|
quantity: number;
|
||||||
|
price: number;
|
||||||
|
portfolioValue: number;
|
||||||
|
}): Observable<{ success: boolean; data: RiskEvaluation }> {
|
||||||
|
return this.http.post<{ success: boolean; data: RiskEvaluation }>(
|
||||||
|
`${this.baseUrls.riskGuardian}/api/risk/evaluate`,
|
||||||
|
params
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
getRiskHistory(): Observable<{ success: boolean; data: RiskEvaluation[] }> {
|
||||||
|
return this.http.get<{ success: boolean; data: RiskEvaluation[] }>(
|
||||||
|
`${this.baseUrls.riskGuardian}/api/risk/history`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy Orchestrator API
|
||||||
|
getStrategies(): Observable<{ success: boolean; data: any[] }> {
|
||||||
|
return this.http.get<{ success: boolean; data: any[] }>(
|
||||||
|
`${this.baseUrls.strategyOrchestrator}/api/strategies`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
createStrategy(strategy: any): Observable<{ success: boolean; data: any }> {
|
||||||
|
return this.http.post<{ success: boolean; data: any }>(
|
||||||
|
`${this.baseUrls.strategyOrchestrator}/api/strategies`,
|
||||||
|
strategy
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Market Data Gateway API
|
||||||
|
getMarketData(
|
||||||
|
symbols: string[] = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'AMZN']
|
||||||
|
): Observable<{ success: boolean; data: MarketData[] }> {
|
||||||
|
const symbolsParam = symbols.join(',');
|
||||||
|
return this.http.get<{ success: boolean; data: MarketData[] }>(
|
||||||
|
`${this.baseUrls.marketDataGateway}/api/market-data?symbols=${symbolsParam}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Health checks
|
||||||
|
checkServiceHealth(
|
||||||
|
service: 'riskGuardian' | 'strategyOrchestrator' | 'marketDataGateway'
|
||||||
|
): Observable<any> {
|
||||||
|
return this.http.get(`${this.baseUrls[service]}/health`);
|
||||||
|
}
|
||||||
|
}
|
||||||
191
apps/dashboard/src/app/services/notification.service.ts
Normal file
191
apps/dashboard/src/app/services/notification.service.ts
Normal file
|
|
@ -0,0 +1,191 @@
|
||||||
|
import { inject, Injectable, signal } from '@angular/core';
|
||||||
|
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||||
|
import { Subscription } from 'rxjs';
|
||||||
|
import { RiskAlert, WebSocketService } from './websocket.service';
|
||||||
|
|
||||||
|
export interface Notification {
|
||||||
|
id: string;
|
||||||
|
type: 'info' | 'warning' | 'error' | 'success';
|
||||||
|
title: string;
|
||||||
|
message: string;
|
||||||
|
timestamp: Date;
|
||||||
|
read: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class NotificationService {
|
||||||
|
private snackBar = inject(MatSnackBar);
|
||||||
|
private webSocketService = inject(WebSocketService);
|
||||||
|
private riskAlertsSubscription?: Subscription;
|
||||||
|
|
||||||
|
// Reactive state
|
||||||
|
public notifications = signal<Notification[]>([]);
|
||||||
|
public unreadCount = signal<number>(0);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.initializeRiskAlerts();
|
||||||
|
}
|
||||||
|
|
||||||
|
private initializeRiskAlerts() {
|
||||||
|
// Subscribe to risk alerts from WebSocket
|
||||||
|
this.riskAlertsSubscription = this.webSocketService.getRiskAlerts().subscribe({
|
||||||
|
next: (alert: RiskAlert) => {
|
||||||
|
this.handleRiskAlert(alert);
|
||||||
|
},
|
||||||
|
error: err => {
|
||||||
|
console.error('Risk alert subscription error:', err);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleRiskAlert(alert: RiskAlert) {
|
||||||
|
const notification: Notification = {
|
||||||
|
id: alert.id,
|
||||||
|
type: this.mapSeverityToType(alert.severity),
|
||||||
|
title: `Risk Alert: ${alert.symbol}`,
|
||||||
|
message: alert.message,
|
||||||
|
timestamp: new Date(alert.timestamp),
|
||||||
|
read: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.addNotification(notification);
|
||||||
|
this.showSnackBarAlert(notification);
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapSeverityToType(severity: string): 'info' | 'warning' | 'error' | 'success' {
|
||||||
|
switch (severity) {
|
||||||
|
case 'HIGH':
|
||||||
|
return 'error';
|
||||||
|
case 'MEDIUM':
|
||||||
|
return 'warning';
|
||||||
|
case 'LOW':
|
||||||
|
return 'info';
|
||||||
|
default:
|
||||||
|
return 'info';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private showSnackBarAlert(notification: Notification) {
|
||||||
|
const actionText = notification.type === 'error' ? 'Review' : 'Dismiss';
|
||||||
|
const duration = notification.type === 'error' ? 10000 : 5000;
|
||||||
|
|
||||||
|
this.snackBar.open(`${notification.title}: ${notification.message}`, actionText, {
|
||||||
|
duration,
|
||||||
|
panelClass: [`snack-${notification.type}`],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public methods
|
||||||
|
addNotification(notification: Notification) {
|
||||||
|
const current = this.notifications();
|
||||||
|
const updated = [notification, ...current].slice(0, 50); // Keep only latest 50
|
||||||
|
this.notifications.set(updated);
|
||||||
|
this.updateUnreadCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
markAsRead(notificationId: string) {
|
||||||
|
const current = this.notifications();
|
||||||
|
const updated = current.map(n => (n.id === notificationId ? { ...n, read: true } : n));
|
||||||
|
this.notifications.set(updated);
|
||||||
|
this.updateUnreadCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
markAllAsRead() {
|
||||||
|
const current = this.notifications();
|
||||||
|
const updated = current.map(n => ({ ...n, read: true }));
|
||||||
|
this.notifications.set(updated);
|
||||||
|
this.updateUnreadCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
clearNotification(notificationId: string) {
|
||||||
|
const current = this.notifications();
|
||||||
|
const updated = current.filter(n => n.id !== notificationId);
|
||||||
|
this.notifications.set(updated);
|
||||||
|
this.updateUnreadCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
clearAllNotifications() {
|
||||||
|
this.notifications.set([]);
|
||||||
|
this.unreadCount.set(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateUnreadCount() {
|
||||||
|
const unread = this.notifications().filter(n => !n.read).length;
|
||||||
|
this.unreadCount.set(unread);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Manual notification methods
|
||||||
|
showSuccess(title: string, message: string) {
|
||||||
|
const notification: Notification = {
|
||||||
|
id: this.generateId(),
|
||||||
|
type: 'success',
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
timestamp: new Date(),
|
||||||
|
read: false,
|
||||||
|
};
|
||||||
|
this.addNotification(notification);
|
||||||
|
this.snackBar.open(`${title}: ${message}`, 'Dismiss', {
|
||||||
|
duration: 3000,
|
||||||
|
panelClass: ['snack-success'],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
showError(title: string, message: string) {
|
||||||
|
const notification: Notification = {
|
||||||
|
id: this.generateId(),
|
||||||
|
type: 'error',
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
timestamp: new Date(),
|
||||||
|
read: false,
|
||||||
|
};
|
||||||
|
this.addNotification(notification);
|
||||||
|
this.snackBar.open(`${title}: ${message}`, 'Dismiss', {
|
||||||
|
duration: 8000,
|
||||||
|
panelClass: ['snack-error'],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
showWarning(title: string, message: string) {
|
||||||
|
const notification: Notification = {
|
||||||
|
id: this.generateId(),
|
||||||
|
type: 'warning',
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
timestamp: new Date(),
|
||||||
|
read: false,
|
||||||
|
};
|
||||||
|
this.addNotification(notification);
|
||||||
|
this.snackBar.open(`${title}: ${message}`, 'Dismiss', {
|
||||||
|
duration: 5000,
|
||||||
|
panelClass: ['snack-warning'],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
showInfo(title: string, message: string) {
|
||||||
|
const notification: Notification = {
|
||||||
|
id: this.generateId(),
|
||||||
|
type: 'info',
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
timestamp: new Date(),
|
||||||
|
read: false,
|
||||||
|
};
|
||||||
|
this.addNotification(notification);
|
||||||
|
this.snackBar.open(`${title}: ${message}`, 'Dismiss', {
|
||||||
|
duration: 4000,
|
||||||
|
panelClass: ['snack-info'],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateId(): string {
|
||||||
|
return Date.now().toString(36) + Math.random().toString(36).substr(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy() {
|
||||||
|
this.riskAlertsSubscription?.unsubscribe();
|
||||||
|
}
|
||||||
|
}
|
||||||
238
apps/dashboard/src/app/services/strategy.service.ts
Normal file
238
apps/dashboard/src/app/services/strategy.service.ts
Normal file
|
|
@ -0,0 +1,238 @@
|
||||||
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
export interface TradingStrategy {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
status: 'ACTIVE' | 'INACTIVE' | 'PAUSED' | 'ERROR';
|
||||||
|
type: string;
|
||||||
|
symbols: string[];
|
||||||
|
parameters: Record<string, any>;
|
||||||
|
performance: {
|
||||||
|
totalTrades: number;
|
||||||
|
winRate: number;
|
||||||
|
totalReturn: number;
|
||||||
|
sharpeRatio: number;
|
||||||
|
maxDrawdown: number;
|
||||||
|
};
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BacktestRequest {
|
||||||
|
strategyType: string;
|
||||||
|
strategyParams: Record<string, any>;
|
||||||
|
symbols: string[];
|
||||||
|
startDate: Date | string;
|
||||||
|
endDate: Date | string;
|
||||||
|
initialCapital: number;
|
||||||
|
dataResolution: '1m' | '5m' | '15m' | '30m' | '1h' | '4h' | '1d';
|
||||||
|
commission: number;
|
||||||
|
slippage: number;
|
||||||
|
mode: 'event' | 'vector';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BacktestResult {
|
||||||
|
strategyId: string;
|
||||||
|
startDate: Date;
|
||||||
|
endDate: Date;
|
||||||
|
duration: number;
|
||||||
|
initialCapital: number;
|
||||||
|
finalCapital: number;
|
||||||
|
totalReturn: number;
|
||||||
|
annualizedReturn: number;
|
||||||
|
sharpeRatio: number;
|
||||||
|
maxDrawdown: number;
|
||||||
|
maxDrawdownDuration: number;
|
||||||
|
winRate: number;
|
||||||
|
totalTrades: number;
|
||||||
|
winningTrades: number;
|
||||||
|
losingTrades: number;
|
||||||
|
averageWinningTrade: number;
|
||||||
|
averageLosingTrade: number;
|
||||||
|
profitFactor: number;
|
||||||
|
dailyReturns: Array<{ date: Date; return: number }>;
|
||||||
|
trades: Array<{
|
||||||
|
symbol: string;
|
||||||
|
entryTime: Date;
|
||||||
|
entryPrice: number;
|
||||||
|
exitTime: Date;
|
||||||
|
exitPrice: number;
|
||||||
|
quantity: number;
|
||||||
|
pnl: number;
|
||||||
|
pnlPercent: number;
|
||||||
|
}>;
|
||||||
|
// Advanced metrics
|
||||||
|
sortinoRatio?: number;
|
||||||
|
calmarRatio?: number;
|
||||||
|
omegaRatio?: number;
|
||||||
|
cagr?: number;
|
||||||
|
volatility?: number;
|
||||||
|
ulcerIndex?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ApiResponse<T> {
|
||||||
|
success: boolean;
|
||||||
|
data: T;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class StrategyService {
|
||||||
|
private apiBaseUrl = '/api'; // Will be proxied to the correct backend endpoint
|
||||||
|
|
||||||
|
constructor(private http: HttpClient) {}
|
||||||
|
|
||||||
|
// Strategy Management
|
||||||
|
getStrategies(): Observable<ApiResponse<TradingStrategy[]>> {
|
||||||
|
return this.http.get<ApiResponse<TradingStrategy[]>>(`${this.apiBaseUrl}/strategies`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getStrategy(id: string): Observable<ApiResponse<TradingStrategy>> {
|
||||||
|
return this.http.get<ApiResponse<TradingStrategy>>(`${this.apiBaseUrl}/strategies/${id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
createStrategy(strategy: Partial<TradingStrategy>): Observable<ApiResponse<TradingStrategy>> {
|
||||||
|
return this.http.post<ApiResponse<TradingStrategy>>(`${this.apiBaseUrl}/strategies`, strategy);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateStrategy(
|
||||||
|
id: string,
|
||||||
|
updates: Partial<TradingStrategy>
|
||||||
|
): Observable<ApiResponse<TradingStrategy>> {
|
||||||
|
return this.http.put<ApiResponse<TradingStrategy>>(
|
||||||
|
`${this.apiBaseUrl}/strategies/${id}`,
|
||||||
|
updates
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
startStrategy(id: string): Observable<ApiResponse<TradingStrategy>> {
|
||||||
|
return this.http.post<ApiResponse<TradingStrategy>>(
|
||||||
|
`${this.apiBaseUrl}/strategies/${id}/start`,
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
stopStrategy(id: string): Observable<ApiResponse<TradingStrategy>> {
|
||||||
|
return this.http.post<ApiResponse<TradingStrategy>>(
|
||||||
|
`${this.apiBaseUrl}/strategies/${id}/stop`,
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pauseStrategy(id: string): Observable<ApiResponse<TradingStrategy>> {
|
||||||
|
return this.http.post<ApiResponse<TradingStrategy>>(
|
||||||
|
`${this.apiBaseUrl}/strategies/${id}/pause`,
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backtest Management
|
||||||
|
getStrategyTypes(): Observable<ApiResponse<string[]>> {
|
||||||
|
return this.http.get<ApiResponse<string[]>>(`${this.apiBaseUrl}/strategy-types`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getStrategyParameters(type: string): Observable<ApiResponse<Record<string, any>>> {
|
||||||
|
return this.http.get<ApiResponse<Record<string, any>>>(
|
||||||
|
`${this.apiBaseUrl}/strategy-parameters/${type}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
runBacktest(request: BacktestRequest): Observable<ApiResponse<BacktestResult>> {
|
||||||
|
return this.http.post<ApiResponse<BacktestResult>>(`${this.apiBaseUrl}/backtest`, request);
|
||||||
|
}
|
||||||
|
getBacktestResult(id: string): Observable<ApiResponse<BacktestResult>> {
|
||||||
|
return this.http.get<ApiResponse<BacktestResult>>(`${this.apiBaseUrl}/backtest/${id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
optimizeStrategy(
|
||||||
|
baseRequest: BacktestRequest,
|
||||||
|
parameterGrid: Record<string, any[]>
|
||||||
|
): Observable<ApiResponse<Array<BacktestResult & { parameters: Record<string, any> }>>> {
|
||||||
|
return this.http.post<ApiResponse<Array<BacktestResult & { parameters: Record<string, any> }>>>(
|
||||||
|
`${this.apiBaseUrl}/backtest/optimize`,
|
||||||
|
{ baseRequest, parameterGrid }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy Signals and Trades
|
||||||
|
getStrategySignals(strategyId: string): Observable<
|
||||||
|
ApiResponse<
|
||||||
|
Array<{
|
||||||
|
id: string;
|
||||||
|
strategyId: string;
|
||||||
|
symbol: string;
|
||||||
|
action: string;
|
||||||
|
price: number;
|
||||||
|
quantity: number;
|
||||||
|
timestamp: Date;
|
||||||
|
confidence: number;
|
||||||
|
metadata?: any;
|
||||||
|
}>
|
||||||
|
>
|
||||||
|
> {
|
||||||
|
return this.http.get<ApiResponse<any[]>>(`${this.apiBaseUrl}/strategies/${strategyId}/signals`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getStrategyTrades(strategyId: string): Observable<
|
||||||
|
ApiResponse<
|
||||||
|
Array<{
|
||||||
|
id: string;
|
||||||
|
strategyId: string;
|
||||||
|
symbol: string;
|
||||||
|
entryPrice: number;
|
||||||
|
entryTime: Date;
|
||||||
|
exitPrice: number;
|
||||||
|
exitTime: Date;
|
||||||
|
quantity: number;
|
||||||
|
pnl: number;
|
||||||
|
pnlPercent: number;
|
||||||
|
}>
|
||||||
|
>
|
||||||
|
> {
|
||||||
|
return this.http.get<ApiResponse<any[]>>(`${this.apiBaseUrl}/strategies/${strategyId}/trades`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper methods for common transformations
|
||||||
|
formatBacktestRequest(formData: any): BacktestRequest {
|
||||||
|
// Handle date formatting and parameter conversion
|
||||||
|
return {
|
||||||
|
...formData,
|
||||||
|
startDate:
|
||||||
|
formData.startDate instanceof Date ? formData.startDate.toISOString() : formData.startDate,
|
||||||
|
endDate: formData.endDate instanceof Date ? formData.endDate.toISOString() : formData.endDate,
|
||||||
|
strategyParams: this.convertParameterTypes(formData.strategyType, formData.strategyParams),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private convertParameterTypes(
|
||||||
|
strategyType: string,
|
||||||
|
params: Record<string, any>
|
||||||
|
): Record<string, any> {
|
||||||
|
// Convert string parameters to correct types based on strategy requirements
|
||||||
|
const result: Record<string, any> = {};
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(params)) {
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
// Try to convert to number if it looks like a number
|
||||||
|
if (!isNaN(Number(value))) {
|
||||||
|
result[key] = Number(value);
|
||||||
|
} else if (value.toLowerCase() === 'true') {
|
||||||
|
result[key] = true;
|
||||||
|
} else if (value.toLowerCase() === 'false') {
|
||||||
|
result[key] = false;
|
||||||
|
} else {
|
||||||
|
result[key] = value;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
215
apps/dashboard/src/app/services/websocket.service.ts
Normal file
215
apps/dashboard/src/app/services/websocket.service.ts
Normal file
|
|
@ -0,0 +1,215 @@
|
||||||
|
import { Injectable, signal } from '@angular/core';
|
||||||
|
import { Observable, Subject } from 'rxjs';
|
||||||
|
import { filter, map } from 'rxjs/operators';
|
||||||
|
|
||||||
|
export interface WebSocketMessage {
|
||||||
|
type: string;
|
||||||
|
data: any;
|
||||||
|
timestamp: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MarketDataUpdate {
|
||||||
|
symbol: string;
|
||||||
|
price: number;
|
||||||
|
change: number;
|
||||||
|
changePercent: number;
|
||||||
|
volume: number;
|
||||||
|
timestamp: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiskAlert {
|
||||||
|
id: string;
|
||||||
|
symbol: string;
|
||||||
|
alertType: 'POSITION_LIMIT' | 'DAILY_LOSS' | 'VOLATILITY' | 'PORTFOLIO_RISK';
|
||||||
|
message: string;
|
||||||
|
severity: 'LOW' | 'MEDIUM' | 'HIGH';
|
||||||
|
timestamp: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class WebSocketService {
|
||||||
|
private readonly WS_ENDPOINTS = {
|
||||||
|
marketData: 'ws://localhost:3001/ws',
|
||||||
|
riskGuardian: 'ws://localhost:3002/ws',
|
||||||
|
strategyOrchestrator: 'ws://localhost:3003/ws',
|
||||||
|
};
|
||||||
|
|
||||||
|
private connections = new Map<string, WebSocket>();
|
||||||
|
private messageSubjects = new Map<string, Subject<WebSocketMessage>>();
|
||||||
|
|
||||||
|
// Connection status signals
|
||||||
|
public isConnected = signal<boolean>(false);
|
||||||
|
public connectionStatus = signal<{ [key: string]: boolean }>({
|
||||||
|
marketData: false,
|
||||||
|
riskGuardian: false,
|
||||||
|
strategyOrchestrator: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.initializeConnections();
|
||||||
|
}
|
||||||
|
|
||||||
|
private initializeConnections() {
|
||||||
|
// Initialize WebSocket connections for all services
|
||||||
|
Object.entries(this.WS_ENDPOINTS).forEach(([service, url]) => {
|
||||||
|
this.connect(service, url);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private connect(serviceName: string, url: string) {
|
||||||
|
try {
|
||||||
|
const ws = new WebSocket(url);
|
||||||
|
const messageSubject = new Subject<WebSocketMessage>();
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
console.log(`Connected to ${serviceName} WebSocket`);
|
||||||
|
this.updateConnectionStatus(serviceName, true);
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onmessage = event => {
|
||||||
|
try {
|
||||||
|
const message: WebSocketMessage = JSON.parse(event.data);
|
||||||
|
messageSubject.next(message);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to parse WebSocket message from ${serviceName}:`, error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onclose = () => {
|
||||||
|
console.log(`Disconnected from ${serviceName} WebSocket`);
|
||||||
|
this.updateConnectionStatus(serviceName, false);
|
||||||
|
|
||||||
|
// Attempt to reconnect after 5 seconds
|
||||||
|
setTimeout(() => {
|
||||||
|
this.connect(serviceName, url);
|
||||||
|
}, 5000);
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onerror = error => {
|
||||||
|
console.error(`WebSocket error for ${serviceName}:`, error);
|
||||||
|
this.updateConnectionStatus(serviceName, false);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.connections.set(serviceName, ws);
|
||||||
|
this.messageSubjects.set(serviceName, messageSubject);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to connect to ${serviceName} WebSocket:`, error);
|
||||||
|
this.updateConnectionStatus(serviceName, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateConnectionStatus(serviceName: string, isConnected: boolean) {
|
||||||
|
const currentStatus = this.connectionStatus();
|
||||||
|
const newStatus = { ...currentStatus, [serviceName]: isConnected };
|
||||||
|
this.connectionStatus.set(newStatus);
|
||||||
|
|
||||||
|
// Update overall connection status
|
||||||
|
const overallConnected = Object.values(newStatus).some(status => status);
|
||||||
|
this.isConnected.set(overallConnected);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Market Data Updates
|
||||||
|
getMarketDataUpdates(): Observable<MarketDataUpdate> {
|
||||||
|
const subject = this.messageSubjects.get('marketData');
|
||||||
|
if (!subject) {
|
||||||
|
throw new Error('Market data WebSocket not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
return subject.asObservable().pipe(
|
||||||
|
filter(message => message.type === 'market_data_update'),
|
||||||
|
map(message => message.data as MarketDataUpdate)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Risk Alerts
|
||||||
|
getRiskAlerts(): Observable<RiskAlert> {
|
||||||
|
const subject = this.messageSubjects.get('riskGuardian');
|
||||||
|
if (!subject) {
|
||||||
|
throw new Error('Risk Guardian WebSocket not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
return subject.asObservable().pipe(
|
||||||
|
filter(message => message.type === 'risk_alert'),
|
||||||
|
map(message => message.data as RiskAlert)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Strategy Updates
|
||||||
|
getStrategyUpdates(): Observable<any> {
|
||||||
|
const subject = this.messageSubjects.get('strategyOrchestrator');
|
||||||
|
if (!subject) {
|
||||||
|
throw new Error('Strategy Orchestrator WebSocket not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
return subject.asObservable().pipe(
|
||||||
|
filter(message => message.type === 'strategy_update'),
|
||||||
|
map(message => message.data)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy Signals
|
||||||
|
getStrategySignals(strategyId?: string): Observable<any> {
|
||||||
|
const subject = this.messageSubjects.get('strategyOrchestrator');
|
||||||
|
if (!subject) {
|
||||||
|
throw new Error('Strategy Orchestrator WebSocket not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
return subject.asObservable().pipe(
|
||||||
|
filter(
|
||||||
|
message =>
|
||||||
|
message.type === 'strategy_signal' &&
|
||||||
|
(!strategyId || message.data.strategyId === strategyId)
|
||||||
|
),
|
||||||
|
map(message => message.data)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy Trades
|
||||||
|
getStrategyTrades(strategyId?: string): Observable<any> {
|
||||||
|
const subject = this.messageSubjects.get('strategyOrchestrator');
|
||||||
|
if (!subject) {
|
||||||
|
throw new Error('Strategy Orchestrator WebSocket not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
return subject.asObservable().pipe(
|
||||||
|
filter(
|
||||||
|
message =>
|
||||||
|
message.type === 'strategy_trade' &&
|
||||||
|
(!strategyId || message.data.strategyId === strategyId)
|
||||||
|
),
|
||||||
|
map(message => message.data)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// All strategy-related messages, useful for components that need all types
|
||||||
|
getAllStrategyMessages(): Observable<WebSocketMessage> {
|
||||||
|
const subject = this.messageSubjects.get('strategyOrchestrator');
|
||||||
|
if (!subject) {
|
||||||
|
throw new Error('Strategy Orchestrator WebSocket not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
return subject.asObservable().pipe(filter(message => message.type.startsWith('strategy_')));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send messages
|
||||||
|
sendMessage(serviceName: string, message: any) {
|
||||||
|
const ws = this.connections.get(serviceName);
|
||||||
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.send(JSON.stringify(message));
|
||||||
|
} else {
|
||||||
|
console.warn(`Cannot send message to ${serviceName}: WebSocket not connected`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cleanup
|
||||||
|
disconnect() {
|
||||||
|
this.connections.forEach((ws, _serviceName) => {
|
||||||
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.connections.clear();
|
||||||
|
this.messageSubjects.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
0
apps/dashboard/src/components/DashboardLayout.tsx
Normal file
0
apps/dashboard/src/components/DashboardLayout.tsx
Normal file
0
apps/dashboard/src/components/TradingDashboard.tsx
Normal file
0
apps/dashboard/src/components/TradingDashboard.tsx
Normal file
0
apps/dashboard/src/index.css
Normal file
0
apps/dashboard/src/index.css
Normal file
16
apps/dashboard/src/index.html
Normal file
16
apps/dashboard/src/index.html
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Trading Dashboard</title>
|
||||||
|
<base href="/">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<link rel="icon" type="image/x-icon" href="favicon.ico">
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||||
|
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com">
|
||||||
|
</head>
|
||||||
|
<body class="mat-typography">
|
||||||
|
<app-root></app-root>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
5
apps/dashboard/src/main.ts
Normal file
5
apps/dashboard/src/main.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
import { bootstrapApplication } from '@angular/platform-browser';
|
||||||
|
import { App } from './app/app';
|
||||||
|
import { appConfig } from './app/app.config';
|
||||||
|
|
||||||
|
bootstrapApplication(App, appConfig).catch(err => console.error(err));
|
||||||
89
apps/dashboard/src/styles.css
Normal file
89
apps/dashboard/src/styles.css
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
/* Custom base styles */
|
||||||
|
html, body {
|
||||||
|
height: 100%;
|
||||||
|
margin: 0;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||||
|
background-color: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Angular Material integration styles */
|
||||||
|
.mat-sidenav-container {
|
||||||
|
background-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-sidenav {
|
||||||
|
border-radius: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-toolbar {
|
||||||
|
background-color: white;
|
||||||
|
color: #374151;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-button.w-full {
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-card {
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-tab-group .mat-mdc-tab-header {
|
||||||
|
border-bottom: 1px solid #e5e7eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-chip.chip-green {
|
||||||
|
background-color: #dcfce7 !important;
|
||||||
|
color: #166534 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-chip.chip-blue {
|
||||||
|
background-color: #dbeafe !important;
|
||||||
|
color: #1e40af !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-table {
|
||||||
|
border-radius: 8px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-header-row {
|
||||||
|
background-color: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-mdc-row:hover {
|
||||||
|
background-color: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Dark mode overrides */
|
||||||
|
.dark .mat-toolbar {
|
||||||
|
background-color: #1f2937;
|
||||||
|
color: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark .mat-mdc-tab-group .mat-mdc-tab-header {
|
||||||
|
border-bottom: 1px solid #4b5563;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark .mat-mdc-header-row {
|
||||||
|
background-color: #1f2937;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark .mat-mdc-row:hover {
|
||||||
|
background-color: #374151;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark .mat-mdc-card {
|
||||||
|
background-color: #1f2937;
|
||||||
|
color: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark .mat-mdc-table {
|
||||||
|
background-color: #1f2937;
|
||||||
|
color: #f9fafb;
|
||||||
|
}
|
||||||
0
apps/dashboard/src/styles.scss
Normal file
0
apps/dashboard/src/styles.scss
Normal file
52
apps/dashboard/tailwind.config.js
Normal file
52
apps/dashboard/tailwind.config.js
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
module.exports = {
|
||||||
|
content: [
|
||||||
|
"./src/**/*.{html,ts}",
|
||||||
|
],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
primary: {
|
||||||
|
50: '#eff6ff',
|
||||||
|
100: '#dbeafe',
|
||||||
|
200: '#bfdbfe',
|
||||||
|
300: '#93c5fd',
|
||||||
|
400: '#60a5fa',
|
||||||
|
500: '#3b82f6',
|
||||||
|
600: '#2563eb',
|
||||||
|
700: '#1d4ed8',
|
||||||
|
800: '#1e40af',
|
||||||
|
900: '#1e3a8a',
|
||||||
|
950: '#172554',
|
||||||
|
},
|
||||||
|
success: {
|
||||||
|
50: '#f0fdf4',
|
||||||
|
100: '#dcfce7',
|
||||||
|
200: '#bbf7d0',
|
||||||
|
300: '#86efac',
|
||||||
|
400: '#4ade80',
|
||||||
|
500: '#22c55e',
|
||||||
|
600: '#16a34a',
|
||||||
|
700: '#15803d',
|
||||||
|
800: '#166534',
|
||||||
|
900: '#14532d',
|
||||||
|
950: '#052e16',
|
||||||
|
},
|
||||||
|
danger: {
|
||||||
|
50: '#fef2f2',
|
||||||
|
100: '#fee2e2',
|
||||||
|
200: '#fecaca',
|
||||||
|
300: '#fca5a5',
|
||||||
|
400: '#f87171',
|
||||||
|
500: '#ef4444',
|
||||||
|
600: '#dc2626',
|
||||||
|
700: '#b91c1c',
|
||||||
|
800: '#991b1b',
|
||||||
|
900: '#7f1d1d',
|
||||||
|
950: '#450a0a',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
}
|
||||||
11
apps/dashboard/tsconfig.app.json
Normal file
11
apps/dashboard/tsconfig.app.json
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
|
||||||
|
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
|
||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"outDir": "./out-tsc/app",
|
||||||
|
"types": []
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts"],
|
||||||
|
"exclude": ["src/**/*.spec.ts"]
|
||||||
|
}
|
||||||
32
apps/dashboard/tsconfig.json
Normal file
32
apps/dashboard/tsconfig.json
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
|
||||||
|
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
|
||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compileOnSave": false,
|
||||||
|
"compilerOptions": {
|
||||||
|
"noImplicitOverride": true,
|
||||||
|
"noPropertyAccessFromIndexSignature": true,
|
||||||
|
"noImplicitReturns": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"importHelpers": true,
|
||||||
|
"module": "preserve"
|
||||||
|
},
|
||||||
|
"angularCompilerOptions": {
|
||||||
|
"enableI18nLegacyMessageIdFormat": false,
|
||||||
|
"strictInjectionParameters": true,
|
||||||
|
"strictInputAccessModifiers": true,
|
||||||
|
"typeCheckHostBindings": true,
|
||||||
|
"strictTemplates": true
|
||||||
|
},
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{
|
||||||
|
"path": "./tsconfig.app.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "./tsconfig.spec.json"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
10
apps/dashboard/tsconfig.spec.json
Normal file
10
apps/dashboard/tsconfig.spec.json
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
|
||||||
|
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
|
||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"outDir": "./out-tsc/spec",
|
||||||
|
"types": ["jasmine"]
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts"]
|
||||||
|
}
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"name": "@stock-bot/data-pipeline",
|
"name": "@stock-bot/data-service",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "Data processing pipeline for syncing and transforming raw data to normalized records",
|
"description": "Combined data ingestion and historical data service",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|
@ -12,23 +12,22 @@
|
||||||
"clean": "rm -rf dist"
|
"clean": "rm -rf dist"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@stock-bot/types": "workspace:*",
|
|
||||||
"@stock-bot/services": "workspace:*",
|
|
||||||
"@stock-bot/cache": "*",
|
"@stock-bot/cache": "*",
|
||||||
"@stock-bot/config": "*",
|
"@stock-bot/config": "*",
|
||||||
"@stock-bot/stock-config": "*",
|
"@stock-bot/event-bus": "*",
|
||||||
|
"@stock-bot/http": "*",
|
||||||
"@stock-bot/logger": "*",
|
"@stock-bot/logger": "*",
|
||||||
"@stock-bot/mongodb": "*",
|
"@stock-bot/mongodb-client": "*",
|
||||||
"@stock-bot/postgres": "*",
|
"@stock-bot/questdb-client": "*",
|
||||||
"@stock-bot/questdb": "*",
|
|
||||||
"@stock-bot/queue": "*",
|
|
||||||
"@stock-bot/shutdown": "*",
|
"@stock-bot/shutdown": "*",
|
||||||
"@stock-bot/handlers": "*",
|
"@stock-bot/types": "*",
|
||||||
"@stock-bot/di": "*",
|
"bullmq": "^5.53.2",
|
||||||
"hono": "^4.0.0",
|
"hono": "^4.0.0",
|
||||||
"@stock-bot/invariants": "workspace:*"
|
"p-limit": "^6.2.0",
|
||||||
|
"ws": "^8.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/ws": "^8.0.0",
|
||||||
"typescript": "^5.0.0"
|
"typescript": "^5.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
112
apps/data-service/src/index.ts
Normal file
112
apps/data-service/src/index.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
/**
|
||||||
|
* Data Service - Combined live and historical data ingestion with queue-based architecture
|
||||||
|
*/
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { Browser } from '@stock-bot/browser';
|
||||||
|
import { loadEnvVariables } from '@stock-bot/config';
|
||||||
|
import { getLogger } from '@stock-bot/logger';
|
||||||
|
import { Shutdown } from '@stock-bot/shutdown';
|
||||||
|
import { initializeIBResources } from './providers/ib.tasks';
|
||||||
|
import { initializeProxyResources } from './providers/proxy.tasks';
|
||||||
|
import { queueManager } from './services/queue.service';
|
||||||
|
import { initializeBatchCache } from './utils/batch-helpers';
|
||||||
|
import { healthRoutes, marketDataRoutes, proxyRoutes, queueRoutes, testRoutes } from './routes';
|
||||||
|
|
||||||
|
// Load environment variables
|
||||||
|
loadEnvVariables();
|
||||||
|
|
||||||
|
const app = new Hono();
|
||||||
|
const logger = getLogger('data-service');
|
||||||
|
const PORT = parseInt(process.env.DATA_SERVICE_PORT || '3002');
|
||||||
|
let server: any = null;
|
||||||
|
|
||||||
|
// Initialize shutdown manager with 15 second timeout
|
||||||
|
const shutdown = Shutdown.getInstance({ timeout: 15000 });
|
||||||
|
|
||||||
|
// Register all routes
|
||||||
|
app.route('', healthRoutes);
|
||||||
|
app.route('', queueRoutes);
|
||||||
|
app.route('', marketDataRoutes);
|
||||||
|
app.route('', proxyRoutes);
|
||||||
|
app.route('', testRoutes);
|
||||||
|
|
||||||
|
// Initialize services
|
||||||
|
async function initializeServices() {
|
||||||
|
logger.info('Initializing data service...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Initialize browser resources
|
||||||
|
logger.info('Starting browser resources initialization...');
|
||||||
|
await Browser.initialize();
|
||||||
|
logger.info('Browser resources initialized');
|
||||||
|
|
||||||
|
// Initialize batch cache FIRST - before queue service
|
||||||
|
logger.info('Starting batch cache initialization...');
|
||||||
|
await initializeBatchCache();
|
||||||
|
logger.info('Batch cache initialized');
|
||||||
|
|
||||||
|
// Initialize proxy cache - before queue service
|
||||||
|
logger.info('Starting proxy cache initialization...');
|
||||||
|
await initializeProxyResources(true); // Wait for cache during startup
|
||||||
|
logger.info('Proxy cache initialized');
|
||||||
|
|
||||||
|
// Initialize proxy cache - before queue service
|
||||||
|
logger.info('Starting proxy cache initialization...');
|
||||||
|
await initializeIBResources(true); // Wait for cache during startup
|
||||||
|
logger.info('Proxy cache initialized');
|
||||||
|
|
||||||
|
// Initialize queue service (Redis connections should be ready now)
|
||||||
|
logger.info('Starting queue service initialization...');
|
||||||
|
await queueManager.initialize();
|
||||||
|
logger.info('Queue service initialized');
|
||||||
|
|
||||||
|
logger.info('All services initialized successfully');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to initialize services', { error });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start server
|
||||||
|
async function startServer() {
|
||||||
|
await initializeServices();
|
||||||
|
// Start the HTTP server using Bun's native serve
|
||||||
|
server = Bun.serve({
|
||||||
|
port: PORT,
|
||||||
|
fetch: app.fetch,
|
||||||
|
development: process.env.NODE_ENV === 'development',
|
||||||
|
});
|
||||||
|
logger.info(`Data Service started on port ${PORT}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register shutdown handlers
|
||||||
|
shutdown.onShutdown(async () => {
|
||||||
|
if (server) {
|
||||||
|
logger.info('Stopping HTTP server...');
|
||||||
|
try {
|
||||||
|
server.stop();
|
||||||
|
logger.info('HTTP server stopped successfully');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Error stopping HTTP server', { error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
shutdown.onShutdown(async () => {
|
||||||
|
logger.info('Shutting down queue manager...');
|
||||||
|
try {
|
||||||
|
await queueManager.shutdown();
|
||||||
|
logger.info('Queue manager shut down successfully');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Error shutting down queue manager', { error });
|
||||||
|
throw error; // Re-throw to mark shutdown as failed
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start the application
|
||||||
|
startServer().catch(error => {
|
||||||
|
logger.error('Failed to start server', { error });
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info('Data service startup initiated with graceful shutdown handlers');
|
||||||
32
apps/data-service/src/providers/ib.provider.ts
Normal file
32
apps/data-service/src/providers/ib.provider.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
import { getLogger } from '@stock-bot/logger';
|
||||||
|
import { ProviderConfig } from '../services/provider-registry.service';
|
||||||
|
|
||||||
|
const logger = getLogger('ib-provider');
|
||||||
|
|
||||||
|
export const ibProvider: ProviderConfig = {
|
||||||
|
name: 'ib',
|
||||||
|
operations: {
|
||||||
|
'ib-symbol-summary': async () => {
|
||||||
|
const { ibTasks } = await import('./ib.tasks');
|
||||||
|
logger.info('Fetching symbol summary from IB');
|
||||||
|
const total = await ibTasks.fetchSymbolSummary();
|
||||||
|
logger.info('Fetched symbol summary from IB', {
|
||||||
|
count: total,
|
||||||
|
});
|
||||||
|
return total;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
scheduledJobs: [
|
||||||
|
{
|
||||||
|
type: 'ib-symbol-summary',
|
||||||
|
operation: 'ib-symbol-summary',
|
||||||
|
payload: {},
|
||||||
|
// should remove and just run at the same time so app restarts dont keeping adding same jobs
|
||||||
|
cronPattern: '*/2 * * * *',
|
||||||
|
priority: 5,
|
||||||
|
immediately: true, // Don't run immediately during startup to avoid conflicts
|
||||||
|
description: 'Fetch and validate proxy list from sources',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
152
apps/data-service/src/providers/ib.tasks.ts
Normal file
152
apps/data-service/src/providers/ib.tasks.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
import { Browser } from '@stock-bot/browser';
|
||||||
|
import { getLogger } from '@stock-bot/logger';
|
||||||
|
|
||||||
|
// Shared instances (module-scoped, not global)
|
||||||
|
let isInitialized = false; // Track if resources are initialized
|
||||||
|
let logger: ReturnType<typeof getLogger>;
|
||||||
|
// let cache: CacheProvider;
|
||||||
|
|
||||||
|
export async function initializeIBResources(waitForCache = false): Promise<void> {
|
||||||
|
// Skip if already initialized
|
||||||
|
if (isInitialized) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger = getLogger('proxy-tasks');
|
||||||
|
// cache = createCache({
|
||||||
|
// keyPrefix: 'proxy:',
|
||||||
|
// ttl: PROXY_CONFIG.CACHE_TTL,
|
||||||
|
// enableMetrics: true,
|
||||||
|
// });
|
||||||
|
|
||||||
|
// httpClient = new HttpClient({ timeout: 15000 }, logger);
|
||||||
|
|
||||||
|
// if (waitForCache) {
|
||||||
|
// // logger.info('Initializing proxy cache...');
|
||||||
|
// // await cache.waitForReady(10000);
|
||||||
|
// // logger.info('Proxy cache initialized successfully');
|
||||||
|
// logger.info('Proxy tasks initialized');
|
||||||
|
// } else {
|
||||||
|
// logger.info('Proxy tasks initialized (fallback mode)');
|
||||||
|
// }
|
||||||
|
isInitialized = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchSymbolSummary(): Promise<number> {
|
||||||
|
try {
|
||||||
|
await Browser.initialize({ headless: true, timeout: 10000, blockResources: false });
|
||||||
|
logger.info('✅ Browser initialized');
|
||||||
|
|
||||||
|
const { page, contextId } = await Browser.createPageWithProxy(
|
||||||
|
'https://www.interactivebrokers.com/en/trading/products-exchanges.php#/',
|
||||||
|
'http://doimvbnb-US-rotate:w5fpiwrb9895@p.webshare.io:80'
|
||||||
|
);
|
||||||
|
logger.info('✅ Page created with proxy');
|
||||||
|
let summaryData: any = null; // Initialize summaryData to store API response
|
||||||
|
let eventCount = 0;
|
||||||
|
page.onNetworkEvent(event => {
|
||||||
|
if (event.url.includes('/webrest/search/product-types/summary')) {
|
||||||
|
console.log(`🎯 Found summary API call: ${event.type} ${event.url}`);
|
||||||
|
|
||||||
|
if (event.type === 'response' && event.responseData) {
|
||||||
|
console.log(`📊 Summary API Response Data: ${event.responseData}`);
|
||||||
|
try {
|
||||||
|
summaryData = JSON.parse(event.responseData) as any;
|
||||||
|
const totalCount = summaryData[0].totalCount;
|
||||||
|
console.log('📊 Summary API Response:', JSON.stringify(summaryData, null, 2));
|
||||||
|
console.log(`🔢 Total symbols found: ${totalCount || 'Unknown'}`);
|
||||||
|
} catch (e) {
|
||||||
|
console.log('📊 Raw Summary Response:', event.responseData);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
eventCount++;
|
||||||
|
logger.info(`📡 Event ${eventCount}: ${event.type} ${event.url}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info('⏳ Waiting for page load...');
|
||||||
|
await page.waitForLoadState('domcontentloaded', { timeout: 20000 });
|
||||||
|
logger.info('✅ Page loaded');
|
||||||
|
|
||||||
|
// RIGHT HERE - Interact with the page to find Stocks checkbox and Apply button
|
||||||
|
logger.info('🔍 Looking for Products tab...');
|
||||||
|
|
||||||
|
// Wait for the page to fully load
|
||||||
|
await page.waitForTimeout(20000);
|
||||||
|
|
||||||
|
// First, click on the Products tab
|
||||||
|
const productsTab = page.locator('#productSearchTab[role="tab"][href="#products"]');
|
||||||
|
await productsTab.waitFor({ timeout: 20000 });
|
||||||
|
logger.info('✅ Found Products tab');
|
||||||
|
|
||||||
|
logger.info('🖱️ Clicking Products tab...');
|
||||||
|
await productsTab.click();
|
||||||
|
logger.info('✅ Products tab clicked');
|
||||||
|
|
||||||
|
// Wait for the tab content to load
|
||||||
|
await page.waitForTimeout(5000);
|
||||||
|
|
||||||
|
// Click on the Asset Classes accordion to expand it
|
||||||
|
logger.info('🔍 Looking for Asset Classes accordion...');
|
||||||
|
const assetClassesAccordion = page.locator(
|
||||||
|
'#products .accordion-item #acc-products .accordion_btn:has-text("Asset Classes")'
|
||||||
|
);
|
||||||
|
await assetClassesAccordion.waitFor({ timeout: 10000 });
|
||||||
|
logger.info('✅ Found Asset Classes accordion');
|
||||||
|
|
||||||
|
logger.info('🖱️ Clicking Asset Classes accordion...');
|
||||||
|
await assetClassesAccordion.click();
|
||||||
|
logger.info('✅ Asset Classes accordion clicked');
|
||||||
|
|
||||||
|
// Wait for the accordion content to expand
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
logger.info('🔍 Looking for Stocks checkbox...');
|
||||||
|
|
||||||
|
// Find the span with class "fs-7 checkbox-text" and inner text containing "Stocks"
|
||||||
|
const stocksSpan = page.locator('span.fs-7.checkbox-text:has-text("Stocks")');
|
||||||
|
await stocksSpan.waitFor({ timeout: 10000 });
|
||||||
|
logger.info('✅ Found Stocks span');
|
||||||
|
|
||||||
|
// Find the checkbox by looking in the same parent container
|
||||||
|
const parentContainer = stocksSpan.locator('..');
|
||||||
|
const checkbox = parentContainer.locator('input[type="checkbox"]');
|
||||||
|
|
||||||
|
if ((await checkbox.count()) > 0) {
|
||||||
|
logger.info('📋 Clicking Stocks checkbox...');
|
||||||
|
await checkbox.first().check();
|
||||||
|
logger.info('✅ Stocks checkbox checked');
|
||||||
|
} else {
|
||||||
|
logger.info('⚠️ Could not find checkbox near Stocks text');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait a moment for any UI updates
|
||||||
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
|
// Find and click the nearest Apply button
|
||||||
|
logger.info('🔍 Looking for Apply button...');
|
||||||
|
const applyButton = page.locator(
|
||||||
|
'button:has-text("Apply"), input[type="submit"][value*="Apply"], input[type="button"][value*="Apply"]'
|
||||||
|
);
|
||||||
|
|
||||||
|
if ((await applyButton.count()) > 0) {
|
||||||
|
logger.info('🎯 Clicking Apply button...');
|
||||||
|
await applyButton.first().click();
|
||||||
|
logger.info('✅ Apply button clicked');
|
||||||
|
|
||||||
|
// Wait for any network requests triggered by the Apply button
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
} else {
|
||||||
|
logger.info('⚠️ Could not find Apply button');
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to fetch IB symbol summary', { error });
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Optional: Export a convenience object that groups related tasks
|
||||||
|
export const ibTasks = {
|
||||||
|
fetchSymbolSummary,
|
||||||
|
};
|
||||||
98
apps/data-service/src/providers/proxy.provider.ts
Normal file
98
apps/data-service/src/providers/proxy.provider.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
||||||
|
import { ProxyInfo } from 'libs/http/src/types';
|
||||||
|
import { getLogger } from '@stock-bot/logger';
|
||||||
|
import { ProviderConfig } from '../services/provider-registry.service';
|
||||||
|
|
||||||
|
// Create logger for this provider
|
||||||
|
const logger = getLogger('proxy-provider');
|
||||||
|
|
||||||
|
// This will run at the same time each day as when the app started
|
||||||
|
const getEvery24HourCron = (): string => {
|
||||||
|
const now = new Date();
|
||||||
|
const hours = now.getHours();
|
||||||
|
const minutes = now.getMinutes();
|
||||||
|
return `${minutes} ${hours} * * *`; // Every day at startup time
|
||||||
|
};
|
||||||
|
|
||||||
|
export const proxyProvider: ProviderConfig = {
|
||||||
|
name: 'proxy-provider',
|
||||||
|
operations: {
|
||||||
|
'fetch-and-check': async (_payload: { sources?: string[] }) => {
|
||||||
|
const { proxyService } = await import('./proxy.tasks');
|
||||||
|
const { queueManager } = await import('../services/queue.service');
|
||||||
|
const { processItems } = await import('../utils/batch-helpers');
|
||||||
|
|
||||||
|
const proxies = await proxyService.fetchProxiesFromSources();
|
||||||
|
|
||||||
|
if (proxies.length === 0) {
|
||||||
|
return { proxiesFetched: 0, jobsCreated: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use generic function with routing parameters
|
||||||
|
const result = await processItems(
|
||||||
|
proxies,
|
||||||
|
(proxy, index) => ({
|
||||||
|
proxy,
|
||||||
|
index,
|
||||||
|
source: 'batch-processing',
|
||||||
|
}),
|
||||||
|
queueManager,
|
||||||
|
{
|
||||||
|
totalDelayHours: 12, //parseFloat(process.env.PROXY_VALIDATION_HOURS || '1'),
|
||||||
|
batchSize: parseInt(process.env.PROXY_BATCH_SIZE || '200'),
|
||||||
|
useBatching: process.env.PROXY_DIRECT_MODE !== 'true',
|
||||||
|
provider: 'proxy-provider',
|
||||||
|
operation: 'check-proxy',
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
'process-batch-items': async (payload: any) => {
|
||||||
|
// Process a batch using the simplified batch helpers
|
||||||
|
const { processBatchJob } = await import('../utils/batch-helpers');
|
||||||
|
const { queueManager } = await import('../services/queue.service');
|
||||||
|
|
||||||
|
return await processBatchJob(payload, queueManager);
|
||||||
|
},
|
||||||
|
|
||||||
|
'check-proxy': async (payload: {
|
||||||
|
proxy: ProxyInfo;
|
||||||
|
source?: string;
|
||||||
|
batchIndex?: number;
|
||||||
|
itemIndex?: number;
|
||||||
|
total?: number;
|
||||||
|
}) => {
|
||||||
|
const { checkProxy } = await import('./proxy.tasks');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await checkProxy(payload.proxy);
|
||||||
|
|
||||||
|
logger.debug('Proxy validated', {
|
||||||
|
proxy: `${payload.proxy.host}:${payload.proxy.port}`,
|
||||||
|
isWorking: result.isWorking,
|
||||||
|
responseTime: result.responseTime,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { result, proxy: payload.proxy };
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('Proxy validation failed', {
|
||||||
|
proxy: `${payload.proxy.host}:${payload.proxy.port}`,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
|
||||||
|
return { result: { isWorking: false, error: String(error) }, proxy: payload.proxy };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
scheduledJobs: [
|
||||||
|
// {
|
||||||
|
// type: 'proxy-maintenance',
|
||||||
|
// operation: 'fetch-and-check',
|
||||||
|
// payload: {},
|
||||||
|
// // should remove and just run at the same time so app restarts dont keeping adding same jobs
|
||||||
|
// cronPattern: getEvery24HourCron(),
|
||||||
|
// priority: 5,
|
||||||
|
// immediately: true, // Don't run immediately during startup to avoid conflicts
|
||||||
|
// description: 'Fetch and validate proxy list from sources',
|
||||||
|
// },
|
||||||
|
],
|
||||||
|
};
|
||||||
574
apps/data-service/src/providers/proxy.tasks.ts
Normal file
574
apps/data-service/src/providers/proxy.tasks.ts
Normal file
|
|
@ -0,0 +1,574 @@
|
||||||
|
import { createCache, type CacheProvider } from '@stock-bot/cache';
|
||||||
|
import { HttpClient, ProxyInfo } from '@stock-bot/http';
|
||||||
|
import { getLogger } from '@stock-bot/logger';
|
||||||
|
|
||||||
|
// Type definitions
|
||||||
|
export interface ProxySource {
|
||||||
|
id: string;
|
||||||
|
url: string;
|
||||||
|
protocol: string;
|
||||||
|
working?: number; // Optional, used for stats
|
||||||
|
total?: number; // Optional, used for stats
|
||||||
|
percentWorking?: number; // Optional, used for stats
|
||||||
|
lastChecked?: Date; // Optional, used for stats
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shared configuration and utilities
|
||||||
|
const PROXY_CONFIG = {
|
||||||
|
CACHE_KEY: 'active',
|
||||||
|
CACHE_STATS_KEY: 'stats',
|
||||||
|
CACHE_TTL: 86400, // 24 hours
|
||||||
|
CHECK_TIMEOUT: 7000,
|
||||||
|
CHECK_IP: '99.246.102.205',
|
||||||
|
CHECK_URL: 'https://proxy-detection.stare.gg/?api_key=bd406bf53ddc6abe1d9de5907830a955',
|
||||||
|
PROXY_SOURCES: [
|
||||||
|
{
|
||||||
|
id: 'prxchk',
|
||||||
|
url: 'https://raw.githubusercontent.com/prxchk/proxy-list/main/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'casals',
|
||||||
|
url: 'https://raw.githubusercontent.com/casals-ar/proxy-list/main/http',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sunny9577',
|
||||||
|
url: 'https://raw.githubusercontent.com/sunny9577/proxy-scraper/master/proxies.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'themiralay',
|
||||||
|
url: 'https://raw.githubusercontent.com/themiralay/Proxy-List-World/refs/heads/master/data.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'casa-ls',
|
||||||
|
url: 'https://raw.githubusercontent.com/casa-ls/proxy-list/refs/heads/main/http',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'databay',
|
||||||
|
url: 'https://raw.githubusercontent.com/databay-labs/free-proxy-list/refs/heads/master/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'speedx',
|
||||||
|
url: 'https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'monosans',
|
||||||
|
url: 'https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'murong',
|
||||||
|
url: 'https://raw.githubusercontent.com/MuRongPIG/Proxy-Master/main/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'vakhov-fresh',
|
||||||
|
url: 'https://raw.githubusercontent.com/vakhov/fresh-proxy-list/master/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'kangproxy',
|
||||||
|
url: 'https://raw.githubusercontent.com/officialputuid/KangProxy/refs/heads/KangProxy/http/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'gfpcom',
|
||||||
|
url: 'https://raw.githubusercontent.com/gfpcom/free-proxy-list/refs/heads/main/list/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'dpangestuw',
|
||||||
|
url: 'https://raw.githubusercontent.com/dpangestuw/Free-Proxy/refs/heads/main/http_proxies.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'gitrecon',
|
||||||
|
url: 'https://raw.githubusercontent.com/gitrecon1455/fresh-proxy-list/refs/heads/main/proxylist.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'vakhov-master',
|
||||||
|
url: 'https://raw.githubusercontent.com/vakhov/fresh-proxy-list/refs/heads/master/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'breaking-tech',
|
||||||
|
url: 'https://raw.githubusercontent.com/BreakingTechFr/Proxy_Free/refs/heads/main/proxies/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ercindedeoglu',
|
||||||
|
url: 'https://raw.githubusercontent.com/ErcinDedeoglu/proxies/main/proxies/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'tuanminpay',
|
||||||
|
url: 'https://raw.githubusercontent.com/TuanMinPay/live-proxy/master/http.txt',
|
||||||
|
protocol: 'http',
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
id: 'r00tee-https',
|
||||||
|
url: 'https://raw.githubusercontent.com/r00tee/Proxy-List/refs/heads/main/Https.txt',
|
||||||
|
protocol: 'https',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ercindedeoglu-https',
|
||||||
|
url: 'https://raw.githubusercontent.com/ErcinDedeoglu/proxies/main/proxies/https.txt',
|
||||||
|
protocol: 'https',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'vakhov-fresh-https',
|
||||||
|
url: 'https://raw.githubusercontent.com/vakhov/fresh-proxy-list/refs/heads/master/https.txt',
|
||||||
|
protocol: 'https',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'databay-https',
|
||||||
|
url: 'https://raw.githubusercontent.com/databay-labs/free-proxy-list/refs/heads/master/https.txt',
|
||||||
|
protocol: 'https',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'kangproxy-https',
|
||||||
|
url: 'https://raw.githubusercontent.com/officialputuid/KangProxy/refs/heads/KangProxy/https/https.txt',
|
||||||
|
protocol: 'https',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'zloi-user-https',
|
||||||
|
url: 'https://raw.githubusercontent.com/zloi-user/hideip.me/refs/heads/master/https.txt',
|
||||||
|
protocol: 'https',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'gfpcom-https',
|
||||||
|
url: 'https://raw.githubusercontent.com/gfpcom/free-proxy-list/refs/heads/main/list/https.txt',
|
||||||
|
protocol: 'https',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Shared instances (module-scoped, not global)
|
||||||
|
let isInitialized = false; // Track if resources are initialized
|
||||||
|
let logger: ReturnType<typeof getLogger>;
|
||||||
|
let cache: CacheProvider;
|
||||||
|
let httpClient: HttpClient;
|
||||||
|
let proxyStats: ProxySource[] = PROXY_CONFIG.PROXY_SOURCES.map(source => ({
|
||||||
|
id: source.id,
|
||||||
|
total: 0,
|
||||||
|
working: 0,
|
||||||
|
lastChecked: new Date(),
|
||||||
|
protocol: source.protocol,
|
||||||
|
url: source.url,
|
||||||
|
}));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize proxy resources (cache and shared dependencies)
|
||||||
|
* This should be called before any proxy operations
|
||||||
|
* @param waitForCache - Whether to wait for cache readiness (default: false for fallback mode)
|
||||||
|
*/
|
||||||
|
export async function initializeProxyResources(waitForCache = false): Promise<void> {
|
||||||
|
// Skip if already initialized
|
||||||
|
if (isInitialized) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger = getLogger('proxy-tasks');
|
||||||
|
cache = createCache({
|
||||||
|
keyPrefix: 'proxy:',
|
||||||
|
ttl: PROXY_CONFIG.CACHE_TTL,
|
||||||
|
enableMetrics: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
httpClient = new HttpClient({ timeout: 10000 }, logger);
|
||||||
|
|
||||||
|
if (waitForCache) {
|
||||||
|
logger.info('Initializing proxy cache...');
|
||||||
|
await cache.waitForReady(10000);
|
||||||
|
logger.info('Proxy cache initialized successfully');
|
||||||
|
logger.info('Proxy tasks initialized');
|
||||||
|
} else {
|
||||||
|
logger.info('Proxy tasks initialized (fallback mode)');
|
||||||
|
}
|
||||||
|
isInitialized = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// make a function that takes in source id and a boolean success and updates the proxyStats array
|
||||||
|
async function updateProxyStats(sourceId: string, success: boolean) {
|
||||||
|
const source = proxyStats.find(s => s.id === sourceId);
|
||||||
|
if (source !== undefined) {
|
||||||
|
if (typeof source.working !== 'number') {
|
||||||
|
source.working = 0;
|
||||||
|
}
|
||||||
|
if (typeof source.total !== 'number') {
|
||||||
|
source.total = 0;
|
||||||
|
}
|
||||||
|
source.total += 1;
|
||||||
|
if (success) {
|
||||||
|
source.working += 1;
|
||||||
|
}
|
||||||
|
source.percentWorking = (source.working / source.total) * 100;
|
||||||
|
source.lastChecked = new Date();
|
||||||
|
await cache.set(`${PROXY_CONFIG.CACHE_STATS_KEY}:${source.id}`, source, PROXY_CONFIG.CACHE_TTL);
|
||||||
|
return source;
|
||||||
|
} else {
|
||||||
|
logger.warn(`Unknown proxy source: ${sourceId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// make a function that resets proxyStats
|
||||||
|
async function resetProxyStats(): Promise<void> {
|
||||||
|
proxyStats = PROXY_CONFIG.PROXY_SOURCES.map(source => ({
|
||||||
|
id: source.id,
|
||||||
|
total: 0,
|
||||||
|
working: 0,
|
||||||
|
lastChecked: new Date(),
|
||||||
|
protocol: source.protocol,
|
||||||
|
url: source.url,
|
||||||
|
}));
|
||||||
|
for (const source of proxyStats) {
|
||||||
|
await cache.set(`${PROXY_CONFIG.CACHE_STATS_KEY}:${source.id}`, source, PROXY_CONFIG.CACHE_TTL);
|
||||||
|
}
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update proxy data in cache with working/total stats and average response time
|
||||||
|
* @param proxy - The proxy to update
|
||||||
|
* @param isWorking - Whether the proxy is currently working
|
||||||
|
*/
|
||||||
|
async function updateProxyInCache(proxy: ProxyInfo, isWorking: boolean): Promise<void> {
|
||||||
|
const cacheKey = `${PROXY_CONFIG.CACHE_KEY}:${proxy.protocol}://${proxy.host}:${proxy.port}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const existing: any = await cache.get(cacheKey);
|
||||||
|
|
||||||
|
// For failed proxies, only update if they already exist
|
||||||
|
if (!isWorking && !existing) {
|
||||||
|
logger.debug('Proxy not in cache, skipping failed update', {
|
||||||
|
proxy: `${proxy.host}:${proxy.port}`,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate new average response time if we have a response time
|
||||||
|
let newAverageResponseTime = existing?.averageResponseTime;
|
||||||
|
if (proxy.responseTime !== undefined) {
|
||||||
|
const existingAvg = existing?.averageResponseTime || 0;
|
||||||
|
const existingTotal = existing?.total || 0;
|
||||||
|
|
||||||
|
// Calculate weighted average: (existing_avg * existing_count + new_response) / (existing_count + 1)
|
||||||
|
newAverageResponseTime =
|
||||||
|
existingTotal > 0
|
||||||
|
? (existingAvg * existingTotal + proxy.responseTime) / (existingTotal + 1)
|
||||||
|
: proxy.responseTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build updated proxy data
|
||||||
|
const updated = {
|
||||||
|
...existing,
|
||||||
|
...proxy, // Keep latest proxy info
|
||||||
|
total: (existing?.total || 0) + 1,
|
||||||
|
working: isWorking ? (existing?.working || 0) + 1 : existing?.working || 0,
|
||||||
|
isWorking,
|
||||||
|
lastChecked: new Date(),
|
||||||
|
// Add firstSeen only for new entries
|
||||||
|
...(existing ? {} : { firstSeen: new Date() }),
|
||||||
|
// Update average response time if we calculated a new one
|
||||||
|
...(newAverageResponseTime !== undefined
|
||||||
|
? { averageResponseTime: newAverageResponseTime }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Calculate success rate
|
||||||
|
updated.successRate = updated.total > 0 ? (updated.working / updated.total) * 100 : 0;
|
||||||
|
|
||||||
|
// Save to cache: reset TTL for working proxies, keep existing TTL for failed ones
|
||||||
|
const cacheOptions = isWorking ? PROXY_CONFIG.CACHE_TTL : undefined;
|
||||||
|
await cache.set(cacheKey, updated, cacheOptions);
|
||||||
|
|
||||||
|
logger.debug(`Updated ${isWorking ? 'working' : 'failed'} proxy in cache`, {
|
||||||
|
proxy: `${proxy.host}:${proxy.port}`,
|
||||||
|
working: updated.working,
|
||||||
|
total: updated.total,
|
||||||
|
successRate: updated.successRate.toFixed(1) + '%',
|
||||||
|
avgResponseTime: updated.averageResponseTime
|
||||||
|
? `${updated.averageResponseTime.toFixed(0)}ms`
|
||||||
|
: 'N/A',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to update proxy in cache', {
|
||||||
|
proxy: `${proxy.host}:${proxy.port}`,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Individual task functions
|
||||||
|
export async function queueProxyFetch(): Promise<string> {
|
||||||
|
const { queueManager } = await import('../services/queue.service');
|
||||||
|
const job = await queueManager.addJob({
|
||||||
|
type: 'proxy-fetch',
|
||||||
|
provider: 'proxy-service',
|
||||||
|
operation: 'fetch-and-check',
|
||||||
|
payload: {},
|
||||||
|
priority: 5,
|
||||||
|
});
|
||||||
|
|
||||||
|
const jobId = job.id || 'unknown';
|
||||||
|
logger.info('Proxy fetch job queued', { jobId });
|
||||||
|
return jobId;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function queueProxyCheck(proxies: ProxyInfo[]): Promise<string> {
|
||||||
|
const { queueManager } = await import('../services/queue.service');
|
||||||
|
const job = await queueManager.addJob({
|
||||||
|
type: 'proxy-check',
|
||||||
|
provider: 'proxy-service',
|
||||||
|
operation: 'check-specific',
|
||||||
|
payload: { proxies },
|
||||||
|
priority: 3,
|
||||||
|
});
|
||||||
|
|
||||||
|
const jobId = job.id || 'unknown';
|
||||||
|
logger.info('Proxy check job queued', { jobId, count: proxies.length });
|
||||||
|
return jobId;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchProxiesFromSources(): Promise<ProxyInfo[]> {
|
||||||
|
await resetProxyStats();
|
||||||
|
const fetchPromises = PROXY_CONFIG.PROXY_SOURCES.map(source => fetchProxiesFromSource(source));
|
||||||
|
const results = await Promise.all(fetchPromises);
|
||||||
|
let allProxies: ProxyInfo[] = results.flat();
|
||||||
|
allProxies = removeDuplicateProxies(allProxies);
|
||||||
|
return allProxies;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchProxiesFromSource(source: ProxySource): Promise<ProxyInfo[]> {
|
||||||
|
const allProxies: ProxyInfo[] = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
logger.info(`Fetching proxies from ${source.url}`);
|
||||||
|
|
||||||
|
const response = await httpClient.get(source.url, {
|
||||||
|
timeout: 10000,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status !== 200) {
|
||||||
|
logger.warn(`Failed to fetch from ${source.url}: ${response.status}`);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = response.data;
|
||||||
|
const lines = text.split('\n').filter((line: string) => line.trim());
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
let trimmed = line.trim();
|
||||||
|
trimmed = cleanProxyUrl(trimmed);
|
||||||
|
if (!trimmed || trimmed.startsWith('#')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse formats like "host:port" or "host:port:user:pass"
|
||||||
|
const parts = trimmed.split(':');
|
||||||
|
if (parts.length >= 2) {
|
||||||
|
const proxy: ProxyInfo = {
|
||||||
|
source: source.id,
|
||||||
|
protocol: source.protocol as 'http' | 'https' | 'socks4' | 'socks5',
|
||||||
|
host: parts[0],
|
||||||
|
port: parseInt(parts[1]),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!isNaN(proxy.port) && proxy.host) {
|
||||||
|
allProxies.push(proxy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`Parsed ${allProxies.length} proxies from ${source.url}`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Error fetching proxies from ${source.url}`, error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return allProxies;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a proxy is working
|
||||||
|
*/
|
||||||
|
export async function checkProxy(proxy: ProxyInfo): Promise<ProxyInfo> {
|
||||||
|
let success = false;
|
||||||
|
logger.debug(`Checking Proxy:`, {
|
||||||
|
protocol: proxy.protocol,
|
||||||
|
host: proxy.host,
|
||||||
|
port: proxy.port,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Test the proxy
|
||||||
|
const response = await httpClient.get(PROXY_CONFIG.CHECK_URL, {
|
||||||
|
proxy,
|
||||||
|
timeout: PROXY_CONFIG.CHECK_TIMEOUT,
|
||||||
|
});
|
||||||
|
|
||||||
|
const isWorking = response.status >= 200 && response.status < 300;
|
||||||
|
const result: ProxyInfo = {
|
||||||
|
...proxy,
|
||||||
|
isWorking,
|
||||||
|
lastChecked: new Date(),
|
||||||
|
responseTime: response.responseTime,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isWorking && !JSON.stringify(response.data).includes(PROXY_CONFIG.CHECK_IP)) {
|
||||||
|
success = true;
|
||||||
|
await updateProxyInCache(result, true);
|
||||||
|
} else {
|
||||||
|
await updateProxyInCache(result, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (proxy.source) {
|
||||||
|
await updateProxyStats(proxy.source, success);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug('Proxy check completed', {
|
||||||
|
host: proxy.host,
|
||||||
|
port: proxy.port,
|
||||||
|
isWorking,
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
const result: ProxyInfo = {
|
||||||
|
...proxy,
|
||||||
|
isWorking: false,
|
||||||
|
error: errorMessage,
|
||||||
|
lastChecked: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update cache for failed proxy (increment total, don't update TTL)
|
||||||
|
await updateProxyInCache(result, false);
|
||||||
|
|
||||||
|
if (proxy.source) {
|
||||||
|
await updateProxyStats(proxy.source, success);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug('Proxy check failed', {
|
||||||
|
host: proxy.host,
|
||||||
|
port: proxy.port,
|
||||||
|
error: errorMessage,
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a random active proxy from the cache
|
||||||
|
* @param protocol - Optional protocol filter ('http' | 'https' | 'socks4' | 'socks5')
|
||||||
|
* @param minSuccessRate - Minimum success rate percentage (default: 50)
|
||||||
|
* @returns A random working proxy or null if none found
|
||||||
|
*/
|
||||||
|
export async function getRandomActiveProxy(
|
||||||
|
protocol?: 'http' | 'https' | 'socks4' | 'socks5',
|
||||||
|
minSuccessRate: number = 50
|
||||||
|
): Promise<ProxyInfo | null> {
|
||||||
|
try {
|
||||||
|
// Get all active proxy keys from cache
|
||||||
|
const pattern = protocol
|
||||||
|
? `${PROXY_CONFIG.CACHE_KEY}:${protocol}://*`
|
||||||
|
: `${PROXY_CONFIG.CACHE_KEY}:*`;
|
||||||
|
|
||||||
|
const keys = await cache.keys(pattern);
|
||||||
|
|
||||||
|
if (keys.length === 0) {
|
||||||
|
logger.debug('No active proxies found in cache', { pattern });
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shuffle the keys for randomness
|
||||||
|
const shuffledKeys = keys.sort(() => Math.random() - 0.5);
|
||||||
|
|
||||||
|
// Find a working proxy that meets the criteria
|
||||||
|
for (const key of shuffledKeys) {
|
||||||
|
try {
|
||||||
|
const proxyData: ProxyInfo | null = await cache.get(key);
|
||||||
|
|
||||||
|
if (
|
||||||
|
proxyData &&
|
||||||
|
proxyData.isWorking &&
|
||||||
|
(!proxyData.successRate || proxyData.successRate >= minSuccessRate)
|
||||||
|
) {
|
||||||
|
logger.debug('Random active proxy selected', {
|
||||||
|
proxy: `${proxyData.host}:${proxyData.port}`,
|
||||||
|
protocol: proxyData.protocol,
|
||||||
|
successRate: proxyData.successRate?.toFixed(1) + '%',
|
||||||
|
avgResponseTime: proxyData.averageResponseTime
|
||||||
|
? `${proxyData.averageResponseTime.toFixed(0)}ms`
|
||||||
|
: 'N/A',
|
||||||
|
});
|
||||||
|
|
||||||
|
return proxyData;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.debug('Error reading proxy from cache', { key, error: (error as Error).message });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug('No working proxies found meeting criteria', {
|
||||||
|
protocol,
|
||||||
|
minSuccessRate,
|
||||||
|
keysChecked: shuffledKeys.length,
|
||||||
|
});
|
||||||
|
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Error getting random active proxy', {
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
protocol,
|
||||||
|
minSuccessRate,
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Utility functions
|
||||||
|
function cleanProxyUrl(url: string): string {
|
||||||
|
return url
|
||||||
|
.replace(/^https?:\/\//, '')
|
||||||
|
.replace(/^0+/, '')
|
||||||
|
.replace(/:0+(\d)/g, ':$1');
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeDuplicateProxies(proxies: ProxyInfo[]): ProxyInfo[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const unique: ProxyInfo[] = [];
|
||||||
|
|
||||||
|
for (const proxy of proxies) {
|
||||||
|
const key = `${proxy.protocol}://${proxy.host}:${proxy.port}`;
|
||||||
|
if (!seen.has(key)) {
|
||||||
|
seen.add(key);
|
||||||
|
unique.push(proxy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return unique;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional: Export a convenience object that groups related tasks
|
||||||
|
export const proxyTasks = {
|
||||||
|
queueProxyFetch,
|
||||||
|
queueProxyCheck,
|
||||||
|
fetchProxiesFromSources,
|
||||||
|
fetchProxiesFromSource,
|
||||||
|
checkProxy,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Export singleton instance for backward compatibility (optional)
|
||||||
|
// Remove this if you want to fully move to the task-based approach
|
||||||
|
export const proxyService = proxyTasks;
|
||||||
182
apps/data-service/src/providers/qm.provider.ts
Normal file
182
apps/data-service/src/providers/qm.provider.ts
Normal file
|
|
@ -0,0 +1,182 @@
|
||||||
|
import { getLogger } from '@stock-bot/logger';
|
||||||
|
import { ProviderConfig } from '../services/provider-registry.service';
|
||||||
|
|
||||||
|
const logger = getLogger('qm-provider');
|
||||||
|
|
||||||
|
export const qmProvider: ProviderConfig = {
|
||||||
|
name: 'qm',
|
||||||
|
operations: {
|
||||||
|
'live-data': async (payload: { symbol: string; fields?: string[] }) => {
|
||||||
|
logger.info('Fetching live data from qm', { symbol: payload.symbol });
|
||||||
|
|
||||||
|
// Simulate qm API call
|
||||||
|
const mockData = {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
price: Math.random() * 1000 + 100,
|
||||||
|
volume: Math.floor(Math.random() * 1000000),
|
||||||
|
change: (Math.random() - 0.5) * 20,
|
||||||
|
changePercent: (Math.random() - 0.5) * 5,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
source: 'qm',
|
||||||
|
fields: payload.fields || ['price', 'volume', 'change'],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Simulate network delay
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100 + Math.random() * 200));
|
||||||
|
|
||||||
|
return mockData;
|
||||||
|
},
|
||||||
|
|
||||||
|
'historical-data': async (payload: {
|
||||||
|
symbol: string;
|
||||||
|
from: Date;
|
||||||
|
to: Date;
|
||||||
|
interval?: string;
|
||||||
|
fields?: string[];
|
||||||
|
}) => {
|
||||||
|
logger.info('Fetching historical data from qm', {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
from: payload.from,
|
||||||
|
to: payload.to,
|
||||||
|
interval: payload.interval || '1d',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Generate mock historical data
|
||||||
|
const days = Math.ceil(
|
||||||
|
(payload.to.getTime() - payload.from.getTime()) / (1000 * 60 * 60 * 24)
|
||||||
|
);
|
||||||
|
const data = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < Math.min(days, 100); i++) {
|
||||||
|
const date = new Date(payload.from.getTime() + i * 24 * 60 * 60 * 1000);
|
||||||
|
data.push({
|
||||||
|
date: date.toISOString().split('T')[0],
|
||||||
|
open: Math.random() * 1000 + 100,
|
||||||
|
high: Math.random() * 1000 + 100,
|
||||||
|
low: Math.random() * 1000 + 100,
|
||||||
|
close: Math.random() * 1000 + 100,
|
||||||
|
volume: Math.floor(Math.random() * 1000000),
|
||||||
|
source: 'qm',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simulate network delay
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 300));
|
||||||
|
|
||||||
|
return {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
interval: payload.interval || '1d',
|
||||||
|
data,
|
||||||
|
source: 'qm',
|
||||||
|
totalRecords: data.length,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
'batch-quotes': async (payload: { symbols: string[]; fields?: string[] }) => {
|
||||||
|
logger.info('Fetching batch quotes from qm', {
|
||||||
|
symbols: payload.symbols,
|
||||||
|
count: payload.symbols.length,
|
||||||
|
});
|
||||||
|
|
||||||
|
const quotes = payload.symbols.map(symbol => ({
|
||||||
|
symbol,
|
||||||
|
price: Math.random() * 1000 + 100,
|
||||||
|
volume: Math.floor(Math.random() * 1000000),
|
||||||
|
change: (Math.random() - 0.5) * 20,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
source: 'qm',
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Simulate network delay
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 300 + Math.random() * 200));
|
||||||
|
|
||||||
|
return {
|
||||||
|
quotes,
|
||||||
|
source: 'qm',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
totalSymbols: payload.symbols.length,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
'company-profile': async (payload: { symbol: string }) => {
|
||||||
|
logger.info('Fetching company profile from qm', { symbol: payload.symbol });
|
||||||
|
|
||||||
|
// Simulate company profile data
|
||||||
|
const profile = {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
companyName: `${payload.symbol} Corporation`,
|
||||||
|
sector: 'Technology',
|
||||||
|
industry: 'Software',
|
||||||
|
description: `${payload.symbol} is a leading technology company.`,
|
||||||
|
marketCap: Math.floor(Math.random() * 1000000000000),
|
||||||
|
employees: Math.floor(Math.random() * 100000),
|
||||||
|
website: `https://www.${payload.symbol.toLowerCase()}.com`,
|
||||||
|
source: 'qm',
|
||||||
|
};
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 150 + Math.random() * 100));
|
||||||
|
|
||||||
|
return profile;
|
||||||
|
},
|
||||||
|
'options-chain': async (payload: { symbol: string; expiration?: string }) => {
|
||||||
|
logger.info('Fetching options chain from qm', {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
expiration: payload.expiration,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Generate mock options data
|
||||||
|
const strikes = Array.from({ length: 20 }, (_, i) => 100 + i * 5);
|
||||||
|
const calls = strikes.map(strike => ({
|
||||||
|
strike,
|
||||||
|
bid: Math.random() * 10,
|
||||||
|
ask: Math.random() * 10 + 0.5,
|
||||||
|
volume: Math.floor(Math.random() * 1000),
|
||||||
|
openInterest: Math.floor(Math.random() * 5000),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const puts = strikes.map(strike => ({
|
||||||
|
strike,
|
||||||
|
bid: Math.random() * 10,
|
||||||
|
ask: Math.random() * 10 + 0.5,
|
||||||
|
volume: Math.floor(Math.random() * 1000),
|
||||||
|
openInterest: Math.floor(Math.random() * 5000),
|
||||||
|
}));
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 400 + Math.random() * 300));
|
||||||
|
return {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
expiration:
|
||||||
|
payload.expiration ||
|
||||||
|
new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
|
||||||
|
calls,
|
||||||
|
puts,
|
||||||
|
source: 'qm',
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
scheduledJobs: [
|
||||||
|
// {
|
||||||
|
// type: 'qm-premium-refresh',
|
||||||
|
// operation: 'batch-quotes',
|
||||||
|
// payload: { symbols: ['AAPL', 'GOOGL', 'MSFT'] },
|
||||||
|
// cronPattern: '*/2 * * * *', // Every 2 minutes
|
||||||
|
// priority: 7,
|
||||||
|
// description: 'Refresh premium quotes with detailed market data'
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// type: 'qm-options-update',
|
||||||
|
// operation: 'options-chain',
|
||||||
|
// payload: { symbol: 'SPY' },
|
||||||
|
// cronPattern: '*/10 * * * *', // Every 10 minutes
|
||||||
|
// priority: 5,
|
||||||
|
// description: 'Update options chain data for SPY ETF'
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// type: 'qm-profiles',
|
||||||
|
// operation: 'company-profile',
|
||||||
|
// payload: { symbol: 'AAPL' },
|
||||||
|
// cronPattern: '0 9 * * 1-5', // Weekdays at 9 AM
|
||||||
|
// priority: 3,
|
||||||
|
// description: 'Update company profile data'
|
||||||
|
// }
|
||||||
|
],
|
||||||
|
};
|
||||||
254
apps/data-service/src/providers/yahoo.provider.ts
Normal file
254
apps/data-service/src/providers/yahoo.provider.ts
Normal file
|
|
@ -0,0 +1,254 @@
|
||||||
|
import { getLogger } from '@stock-bot/logger';
|
||||||
|
import { ProviderConfig } from '../services/provider-registry.service';
|
||||||
|
|
||||||
|
const logger = getLogger('yahoo-provider');
|
||||||
|
|
||||||
|
export const yahooProvider: ProviderConfig = {
|
||||||
|
name: 'yahoo-finance',
|
||||||
|
operations: {
|
||||||
|
'live-data': async (payload: { symbol: string; modules?: string[] }) => {
|
||||||
|
logger.info('Fetching live data from Yahoo Finance', { symbol: payload.symbol });
|
||||||
|
|
||||||
|
// Simulate Yahoo Finance API call
|
||||||
|
const mockData = {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
regularMarketPrice: Math.random() * 1000 + 100,
|
||||||
|
regularMarketVolume: Math.floor(Math.random() * 1000000),
|
||||||
|
regularMarketChange: (Math.random() - 0.5) * 20,
|
||||||
|
regularMarketChangePercent: (Math.random() - 0.5) * 5,
|
||||||
|
preMarketPrice: Math.random() * 1000 + 100,
|
||||||
|
postMarketPrice: Math.random() * 1000 + 100,
|
||||||
|
marketCap: Math.floor(Math.random() * 1000000000000),
|
||||||
|
peRatio: Math.random() * 50 + 5,
|
||||||
|
dividendYield: Math.random() * 0.1,
|
||||||
|
fiftyTwoWeekHigh: Math.random() * 1200 + 100,
|
||||||
|
fiftyTwoWeekLow: Math.random() * 800 + 50,
|
||||||
|
timestamp: Date.now() / 1000,
|
||||||
|
source: 'yahoo-finance',
|
||||||
|
modules: payload.modules || ['price', 'summaryDetail'],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Simulate network delay
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 150 + Math.random() * 250));
|
||||||
|
|
||||||
|
return mockData;
|
||||||
|
},
|
||||||
|
|
||||||
|
'historical-data': async (payload: {
|
||||||
|
symbol: string;
|
||||||
|
period1: number;
|
||||||
|
period2: number;
|
||||||
|
interval?: string;
|
||||||
|
events?: string;
|
||||||
|
}) => {
|
||||||
|
const { getLogger } = await import('@stock-bot/logger');
|
||||||
|
const logger = getLogger('yahoo-provider');
|
||||||
|
|
||||||
|
logger.info('Fetching historical data from Yahoo Finance', {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
period1: payload.period1,
|
||||||
|
period2: payload.period2,
|
||||||
|
interval: payload.interval || '1d',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Generate mock historical data
|
||||||
|
const days = Math.ceil((payload.period2 - payload.period1) / (24 * 60 * 60));
|
||||||
|
const data = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < Math.min(days, 100); i++) {
|
||||||
|
const timestamp = payload.period1 + i * 24 * 60 * 60;
|
||||||
|
data.push({
|
||||||
|
timestamp,
|
||||||
|
date: new Date(timestamp * 1000).toISOString().split('T')[0],
|
||||||
|
open: Math.random() * 1000 + 100,
|
||||||
|
high: Math.random() * 1000 + 100,
|
||||||
|
low: Math.random() * 1000 + 100,
|
||||||
|
close: Math.random() * 1000 + 100,
|
||||||
|
adjClose: Math.random() * 1000 + 100,
|
||||||
|
volume: Math.floor(Math.random() * 1000000),
|
||||||
|
source: 'yahoo-finance',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simulate network delay
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 250 + Math.random() * 350));
|
||||||
|
|
||||||
|
return {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
interval: payload.interval || '1d',
|
||||||
|
timestamps: data.map(d => d.timestamp),
|
||||||
|
indicators: {
|
||||||
|
quote: [
|
||||||
|
{
|
||||||
|
open: data.map(d => d.open),
|
||||||
|
high: data.map(d => d.high),
|
||||||
|
low: data.map(d => d.low),
|
||||||
|
close: data.map(d => d.close),
|
||||||
|
volume: data.map(d => d.volume),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
adjclose: [
|
||||||
|
{
|
||||||
|
adjclose: data.map(d => d.adjClose),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
source: 'yahoo-finance',
|
||||||
|
totalRecords: data.length,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
search: async (payload: { query: string; quotesCount?: number; newsCount?: number }) => {
|
||||||
|
const { getLogger } = await import('@stock-bot/logger');
|
||||||
|
const logger = getLogger('yahoo-provider');
|
||||||
|
|
||||||
|
logger.info('Searching Yahoo Finance', { query: payload.query });
|
||||||
|
|
||||||
|
// Generate mock search results
|
||||||
|
const quotes = Array.from({ length: payload.quotesCount || 5 }, (_, i) => ({
|
||||||
|
symbol: `${payload.query.toUpperCase()}${i}`,
|
||||||
|
shortname: `${payload.query} Company ${i}`,
|
||||||
|
longname: `${payload.query} Corporation ${i}`,
|
||||||
|
exchDisp: 'NASDAQ',
|
||||||
|
typeDisp: 'Equity',
|
||||||
|
source: 'yahoo-finance',
|
||||||
|
}));
|
||||||
|
|
||||||
|
const news = Array.from({ length: payload.newsCount || 3 }, (_, i) => ({
|
||||||
|
uuid: `news-${i}-${Date.now()}`,
|
||||||
|
title: `${payload.query} News Article ${i}`,
|
||||||
|
publisher: 'Financial News',
|
||||||
|
providerPublishTime: Date.now() - i * 3600000,
|
||||||
|
type: 'STORY',
|
||||||
|
source: 'yahoo-finance',
|
||||||
|
}));
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 200));
|
||||||
|
|
||||||
|
return {
|
||||||
|
quotes,
|
||||||
|
news,
|
||||||
|
totalQuotes: quotes.length,
|
||||||
|
totalNews: news.length,
|
||||||
|
source: 'yahoo-finance',
|
||||||
|
};
|
||||||
|
},
|
||||||
|
financials: async (payload: { symbol: string; type?: 'income' | 'balance' | 'cash' }) => {
|
||||||
|
const { getLogger } = await import('@stock-bot/logger');
|
||||||
|
const logger = getLogger('yahoo-provider');
|
||||||
|
|
||||||
|
logger.info('Fetching financials from Yahoo Finance', {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
type: payload.type || 'income',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Generate mock financial data
|
||||||
|
const financials = {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
type: payload.type || 'income',
|
||||||
|
currency: 'USD',
|
||||||
|
annual: Array.from({ length: 4 }, (_, i) => ({
|
||||||
|
fiscalYear: 2024 - i,
|
||||||
|
revenue: Math.floor(Math.random() * 100000000000),
|
||||||
|
netIncome: Math.floor(Math.random() * 10000000000),
|
||||||
|
totalAssets: Math.floor(Math.random() * 500000000000),
|
||||||
|
totalDebt: Math.floor(Math.random() * 50000000000),
|
||||||
|
})),
|
||||||
|
quarterly: Array.from({ length: 4 }, (_, i) => ({
|
||||||
|
fiscalQuarter: `Q${4 - i} 2024`,
|
||||||
|
revenue: Math.floor(Math.random() * 25000000000),
|
||||||
|
netIncome: Math.floor(Math.random() * 2500000000),
|
||||||
|
})),
|
||||||
|
source: 'yahoo-finance',
|
||||||
|
};
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 300 + Math.random() * 200));
|
||||||
|
|
||||||
|
return financials;
|
||||||
|
},
|
||||||
|
earnings: async (payload: { symbol: string; period?: 'annual' | 'quarterly' }) => {
|
||||||
|
const { getLogger } = await import('@stock-bot/logger');
|
||||||
|
const logger = getLogger('yahoo-provider');
|
||||||
|
|
||||||
|
logger.info('Fetching earnings from Yahoo Finance', {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
period: payload.period || 'quarterly',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Generate mock earnings data
|
||||||
|
const earnings = {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
period: payload.period || 'quarterly',
|
||||||
|
earnings: Array.from({ length: 8 }, (_, i) => ({
|
||||||
|
quarter: `Q${(i % 4) + 1} ${2024 - Math.floor(i / 4)}`,
|
||||||
|
epsEstimate: Math.random() * 5,
|
||||||
|
epsActual: Math.random() * 5,
|
||||||
|
revenueEstimate: Math.floor(Math.random() * 50000000000),
|
||||||
|
revenueActual: Math.floor(Math.random() * 50000000000),
|
||||||
|
surprise: (Math.random() - 0.5) * 2,
|
||||||
|
})),
|
||||||
|
source: 'yahoo-finance',
|
||||||
|
};
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 250 + Math.random() * 150));
|
||||||
|
|
||||||
|
return earnings;
|
||||||
|
},
|
||||||
|
recommendations: async (payload: { symbol: string }) => {
|
||||||
|
const { getLogger } = await import('@stock-bot/logger');
|
||||||
|
const logger = getLogger('yahoo-provider');
|
||||||
|
|
||||||
|
logger.info('Fetching recommendations from Yahoo Finance', { symbol: payload.symbol });
|
||||||
|
|
||||||
|
// Generate mock recommendations
|
||||||
|
const recommendations = {
|
||||||
|
symbol: payload.symbol,
|
||||||
|
current: {
|
||||||
|
strongBuy: Math.floor(Math.random() * 10),
|
||||||
|
buy: Math.floor(Math.random() * 15),
|
||||||
|
hold: Math.floor(Math.random() * 20),
|
||||||
|
sell: Math.floor(Math.random() * 5),
|
||||||
|
strongSell: Math.floor(Math.random() * 3),
|
||||||
|
},
|
||||||
|
trend: Array.from({ length: 4 }, (_, i) => ({
|
||||||
|
period: `${i}m`,
|
||||||
|
strongBuy: Math.floor(Math.random() * 10),
|
||||||
|
buy: Math.floor(Math.random() * 15),
|
||||||
|
hold: Math.floor(Math.random() * 20),
|
||||||
|
sell: Math.floor(Math.random() * 5),
|
||||||
|
strongSell: Math.floor(Math.random() * 3),
|
||||||
|
})),
|
||||||
|
source: 'yahoo-finance',
|
||||||
|
};
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 180 + Math.random() * 120));
|
||||||
|
return recommendations;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
scheduledJobs: [
|
||||||
|
// {
|
||||||
|
// type: 'yahoo-market-refresh',
|
||||||
|
// operation: 'live-data',
|
||||||
|
// payload: { symbol: 'AAPL' },
|
||||||
|
// cronPattern: '*/1 * * * *', // Every minute
|
||||||
|
// priority: 8,
|
||||||
|
// description: 'Refresh Apple stock price from Yahoo Finance'
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// type: 'yahoo-sp500-update',
|
||||||
|
// operation: 'live-data',
|
||||||
|
// payload: { symbol: 'SPY' },
|
||||||
|
// cronPattern: '*/2 * * * *', // Every 2 minutes
|
||||||
|
// priority: 9,
|
||||||
|
// description: 'Update S&P 500 ETF price'
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// type: 'yahoo-earnings-check',
|
||||||
|
// operation: 'earnings',
|
||||||
|
// payload: { symbol: 'AAPL' },
|
||||||
|
// cronPattern: '0 16 * * 1-5', // Weekdays at 4 PM (market close)
|
||||||
|
// priority: 6,
|
||||||
|
// description: 'Check earnings data for Apple'
|
||||||
|
// }
|
||||||
|
],
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue