- Database migration 018 with 13 tables for trading engine state - Trading engine service (services/trading/) with 12 pure computation modules: position sizer, stop-loss manager, reserve pool, circuit breaker, risk tier controller, correlation matrix, tax lots, trading window, gradual entry, notifications, micro-trading, backtester - Core TradingEngine with pre-trade evaluation pipeline and integration wiring - FastAPI HTTP service with 14 endpoints (health, config, decisions, metrics, backtest) - Performance tracker with Sharpe ratio, drawdown, profit factor computation - 194 Python tests (165 property-based + 29 integration) - Frontend: 13 TanStack Query hooks, 7 dashboard panels, tabbed Trading Engine page - Helm chart entry, network policy, nginx proxy, ingress for trading-engine - Shared infrastructure: enums, Redis keys, TradingConfig in AppConfig
38 KiB
Requirements Document — Autonomous Trading Engine
Introduction
This feature adds a fully autonomous trading engine to the Stonks Oracle platform. The engine consumes recommendations produced by the existing three-layer signal aggregation pipeline (company-specific, macro, competitive), applies confidence-based position sizing, reserve pool management, dynamic stop-loss/take-profit levels, and portfolio rebalancing logic, then executes trades through the existing Alpaca broker adapter.
The system is designed for a developer who wants to allocate $500 in paper trading capital and let the engine operate without manual intervention. Day-to-day decisions — what to buy, how much, when to exit — are made autonomously based on signal confidence, risk tier configuration, and portfolio state. The architecture supports switching from paper to live trading with minimal changes.
The engine builds on existing infrastructure rather than replacing it. The recommendation engine already produces buy/sell/hold/watch signals with confidence scores and position sizing guidance. The broker service already submits orders to Alpaca with idempotency and risk evaluation. The risk engine already enforces position limits, sector exposure, and daily loss controls. This feature layers autonomous decision-making, reserve pool management, adaptive market response, circuit breakers, and performance tracking on top of that foundation.
Key design principles:
- Fail-safe: circuit breakers halt trading on abnormal losses; reserve pool is untouchable by normal trading
- Transparent: every decision is traced from signal through sizing through execution
- Incremental: positions are built gradually, not all-at-once
- Adaptive: risk tier auto-adjusts based on recent performance and reserve pool health
Glossary
- Trading_Engine: The autonomous service that polls for actionable recommendations, computes position sizes, manages the reserve pool, enforces circuit breakers, and submits orders to the Broker_Service.
- Reserve_Pool: A cash reserve automatically funded by siphoning a configurable percentage of realized profits. The Reserve_Pool is not available for normal trading and acts as a safety net for the portfolio.
- Active_Pool: The portion of portfolio capital available for trading, equal to total portfolio value minus the Reserve_Pool balance.
- Risk_Tier: A named configuration preset (conservative, moderate, aggressive) that controls confidence thresholds, position sizing multipliers, stop-loss widths, and take-profit targets.
- Risk_Tier_Controller: The component that evaluates recent performance metrics and Reserve_Pool size to automatically adjust the active Risk_Tier.
- Circuit_Breaker: A safety mechanism that halts all trading when portfolio losses exceed configurable thresholds within a time window, or when abnormal market conditions are detected.
- Position_Sizer: The component that computes the dollar amount and share quantity for a trade based on signal confidence, Risk_Tier parameters, Active_Pool size, correlation constraints, and sector exposure limits.
- Stop_Loss_Manager: The component that computes and maintains dynamic stop-loss and take-profit levels for each open position based on volatility and signal strength.
- Portfolio_Rebalancer: The component that periodically evaluates portfolio concentration and generates rebalancing orders when sector or single-stock exposure exceeds configurable limits.
- Performance_Tracker: The component that computes and persists real-time portfolio metrics including P&L, win/loss ratio, Sharpe ratio, max drawdown, and per-trade statistics.
- Backtester: The component that replays historical recommendation and market data to simulate how the trading strategy would have performed, producing the same metrics as the Performance_Tracker.
- Portfolio_Heat: The total risk across all open positions, computed as the sum of each position's value multiplied by its stop-loss distance percentage. Portfolio_Heat must not exceed a configurable threshold of the Active_Pool.
- Correlation_Matrix: A precomputed matrix of price correlation coefficients between tracked companies, used to prevent over-concentration in correlated positions.
- Earnings_Calendar: A schedule of upcoming earnings report dates for tracked companies, used to reduce position sizes before earnings and adjust after results.
- Trading_Window: The allowed time range for order submission, excluding the first and last 15 minutes of market hours to avoid high-volatility open/close periods.
- Gradual_Entry: The strategy of scaling into a position over multiple smaller orders rather than a single large order, reducing market impact and allowing the engine to abort if conditions change.
- Tax_Lot: A record of the purchase date, quantity, and cost basis for a specific acquisition of shares, used for tax-loss harvesting awareness and wash sale detection.
- Notification_Service: The component that sends alerts to the operator via SMS (AWS SNS) and email (Gmail API) for critical events such as circuit breaker triggers, risk tier changes, large trades, and daily performance summaries.
- Micro_Trading_Mode: An optional operating mode where the Trading_Engine evaluates and acts on intraday and short-window trend signals (5-minute and 15-minute intervals) in addition to the standard daily/weekly recommendation cycle, enabling faster position turnover for short-term opportunities.
- Broker_Service: The existing service (services/adapters/broker_service.py) that processes order requests through risk evaluation and submits them to Alpaca.
- Recommendation_Engine: The existing service (services/recommendation/) that produces buy/sell/hold/watch signals with confidence scores from trend data.
- Aggregation_Engine: The existing service (services/aggregation/) that computes trend summaries from all three signal layers.
Requirements
Requirement 1: Autonomous Decision Loop
User Story: As a developer with $500 in paper trading capital, I want the system to automatically evaluate recommendations and execute trades without my intervention, so that I can let it run and check results periodically.
Acceptance Criteria
- THE Trading_Engine SHALL run a continuous decision loop that polls for new actionable recommendations (action = buy or sell, mode = paper_eligible or live_eligible) at a configurable interval (default: 60 seconds).
- WHEN the Trading_Engine finds an actionable recommendation, THE Trading_Engine SHALL evaluate the recommendation against the current portfolio state, Risk_Tier parameters, circuit breaker status, and Trading_Window constraints before deciding whether to act.
- WHEN the Trading_Engine decides to act on a recommendation, THE Trading_Engine SHALL compute the position size via the Position_Sizer, generate an order job, and submit it to the existing Broker_Service queue for execution.
- WHEN the Trading_Engine decides not to act on a recommendation, THE Trading_Engine SHALL persist a decision record with the skip reason (circuit breaker active, outside Trading_Window, insufficient confidence, position limit reached, or insufficient Active_Pool funds).
- THE Trading_Engine SHALL process each recommendation at most once, using the recommendation ID as a deduplication key persisted in Redis with a configurable TTL (default: 24 hours).
- WHEN the Trading_Engine starts, THE Trading_Engine SHALL load the current portfolio state from the Broker_Service (positions, account balance) and the active Risk_Tier configuration from PostgreSQL before entering the decision loop.
- THE Trading_Engine SHALL expose a health endpoint at
/healthand a readiness endpoint at/readythat reports whether the engine has successfully loaded portfolio state and is actively polling.
Requirement 2: Confidence-Based Position Sizing
User Story: As a developer, I want position sizes to scale with signal confidence so that high-confidence signals get larger allocations and the system never risks too much on a single trade.
Acceptance Criteria
- WHEN the Position_Sizer computes a trade size, THE Position_Sizer SHALL scale the allocation as a percentage of the Active_Pool using the formula:
base_allocation_pct * (confidence / confidence_threshold) * risk_tier_multiplier, clamped to the Risk_Tier's max_position_pct. - WHEN the signal confidence is below the Risk_Tier's minimum confidence threshold, THE Position_Sizer SHALL return a zero allocation and the Trading_Engine SHALL skip the trade.
- THE Position_Sizer SHALL enforce that no single position exceeds a configurable maximum percentage of the Active_Pool (default: 10% for moderate tier).
- THE Position_Sizer SHALL enforce that the total dollar value of any single position does not exceed a configurable absolute cap (default: $50 for a $500 portfolio, scaling with portfolio size).
- WHEN computing position size, THE Position_Sizer SHALL check the Correlation_Matrix and reduce the allocation if the portfolio already holds positions with a correlation coefficient above 0.7 to the candidate stock.
- WHEN computing position size, THE Position_Sizer SHALL check sector exposure and reduce the allocation if adding the position would cause the sector to exceed the configurable sector exposure limit (default: 30% of Active_Pool).
- THE Position_Sizer SHALL round the computed share quantity down to whole shares and reject orders where the resulting quantity is zero.
Requirement 3: Reserve Pool Management
User Story: As a developer, I want a portion of profits automatically set aside into a reserve that normal trading cannot touch, so that the portfolio has a safety net that grows over time.
Acceptance Criteria
- WHEN a position is closed with a realized profit, THE Trading_Engine SHALL transfer a configurable percentage of the profit (default: 20%) into the Reserve_Pool.
- THE Trading_Engine SHALL persist the Reserve_Pool balance in PostgreSQL and update it on every profit siphon event, with a full audit trail of deposits and withdrawals.
- THE Trading_Engine SHALL compute the Active_Pool as:
total_portfolio_value - reserve_pool_balance, and all position sizing and risk calculations SHALL use the Active_Pool rather than the total portfolio value. - WHEN the Reserve_Pool balance exceeds a configurable high-water mark percentage of the total portfolio (default: 30%), THE Risk_Tier_Controller SHALL consider this a signal to increase risk tolerance (shift toward a more aggressive tier).
- WHEN the Active_Pool drops below a configurable minimum threshold (default: $100), THE Trading_Engine SHALL halt new position entries and only allow position exits until the Active_Pool recovers.
- IF the portfolio experiences a drawdown exceeding a configurable emergency threshold (default: 40% of initial capital), THEN THE Trading_Engine SHALL liquidate the Reserve_Pool into the Active_Pool to provide emergency capital, log the event, and shift to the conservative Risk_Tier.
- THE Reserve_Pool balance SHALL be visible on the dashboard and included in all portfolio summary API responses.
Requirement 4: Dynamic Stop-Loss and Take-Profit
User Story: As a developer, I want every position to have automatic exit levels that adapt to market volatility and signal strength, so that losses are cut and profits are captured without manual monitoring.
Acceptance Criteria
- WHEN the Trading_Engine opens a new position, THE Stop_Loss_Manager SHALL compute an initial stop-loss price based on the stock's recent volatility (ATR — Average True Range over 14 periods) and the Risk_Tier's stop-loss multiplier:
entry_price - (ATR * stop_loss_atr_multiplier)for long positions. - WHEN the Trading_Engine opens a new position, THE Stop_Loss_Manager SHALL compute an initial take-profit price using the Risk_Tier's reward-to-risk ratio:
entry_price + (stop_distance * reward_risk_ratio). - WHILE a position is open, THE Stop_Loss_Manager SHALL re-evaluate stop-loss and take-profit levels at a configurable interval (default: every 5 minutes during market hours) and adjust them if volatility or signal conditions have materially changed.
- WHEN a position's current price crosses the stop-loss level, THE Trading_Engine SHALL submit a market sell order to the Broker_Service immediately, without waiting for the next decision loop cycle.
- WHEN a position's current price crosses the take-profit level, THE Trading_Engine SHALL submit a market sell order to the Broker_Service immediately.
- WHEN a position has moved favorably by more than 50% of the take-profit distance, THE Stop_Loss_Manager SHALL implement a trailing stop by moving the stop-loss to breakeven (entry price) to lock in a risk-free position.
- THE Stop_Loss_Manager SHALL persist all stop-loss and take-profit levels and adjustments in PostgreSQL with timestamps for audit trail purposes.
- IF the Trading_Engine cannot fetch current price data for a position, THEN THE Trading_Engine SHALL use the last known price and log a warning, and if price data is unavailable for more than 15 minutes during market hours, THE Trading_Engine SHALL close the position as a safety measure.
Requirement 5: Risk Tier Configuration and Auto-Adjustment
User Story: As a developer, I want configurable risk tiers that auto-adjust based on how the system is performing, so that the engine takes less risk after losses and more risk when it is doing well.
Acceptance Criteria
- THE Trading_Engine SHALL support three named Risk_Tiers with the following default parameters:
- Conservative: min_confidence = 0.75, max_position_pct = 0.05, stop_loss_atr_multiplier = 1.5, reward_risk_ratio = 2.0, max_sector_pct = 0.20, max_portfolio_heat = 0.10
- Moderate: min_confidence = 0.55, max_position_pct = 0.10, stop_loss_atr_multiplier = 2.0, reward_risk_ratio = 1.5, max_sector_pct = 0.30, max_portfolio_heat = 0.20
- Aggressive: min_confidence = 0.40, max_position_pct = 0.15, stop_loss_atr_multiplier = 2.5, reward_risk_ratio = 1.2, max_sector_pct = 0.40, max_portfolio_heat = 0.30
- THE Risk_Tier_Controller SHALL evaluate the active Risk_Tier at a configurable interval (default: daily at market close) based on: trailing 30-day win rate, trailing 30-day Sharpe ratio, current drawdown from peak portfolio value, and Reserve_Pool size relative to total portfolio.
- WHEN the trailing 30-day win rate drops below 40% or the current drawdown exceeds 15%, THE Risk_Tier_Controller SHALL downgrade the Risk_Tier by one level (aggressive → moderate, moderate → conservative).
- WHEN the trailing 30-day win rate exceeds 55% and the Reserve_Pool exceeds 20% of total portfolio value and the current drawdown is below 5%, THE Risk_Tier_Controller SHALL upgrade the Risk_Tier by one level (conservative → moderate, moderate → aggressive).
- WHEN the Risk_Tier_Controller changes the active Risk_Tier, THE Risk_Tier_Controller SHALL persist the change in PostgreSQL with the previous tier, new tier, and the metrics that triggered the change, and log the event.
- THE Risk_Tier configuration SHALL be stored in PostgreSQL and editable through the API, allowing operators to override the auto-adjustment and manually set a tier.
Requirement 6: Circuit Breakers
User Story: As a developer, I want automatic safety stops that halt all trading if things go badly wrong, so that a bad day or a flash crash does not wipe out the portfolio.
Acceptance Criteria
- WHEN the portfolio value drops by more than a configurable daily loss percentage (default: 5%) within a single trading day, THE Circuit_Breaker SHALL halt all new order submissions and log the event with the loss amount and percentage.
- WHEN a single position loses more than a configurable percentage of its entry value (default: 15%), THE Circuit_Breaker SHALL immediately close the position via a market sell order and prevent the Trading_Engine from re-entering the same ticker for a configurable cooldown period (default: 48 hours).
- WHEN the Circuit_Breaker detects extreme market volatility (VIX equivalent proxy exceeding a configurable threshold, or more than 3 positions hitting stop-losses within a 30-minute window), THE Circuit_Breaker SHALL pause all trading for a configurable duration (default: 2 hours) and log the trigger condition.
- WHEN a Circuit_Breaker is triggered, THE Trading_Engine SHALL send a notification to a configurable alert channel (Redis pub/sub event) and record the circuit breaker event in PostgreSQL with the trigger type, threshold, actual value, and timestamp.
- WHEN a Circuit_Breaker cooldown expires, THE Trading_Engine SHALL resume normal operation automatically and log the resumption.
- THE Circuit_Breaker status (active/inactive, trigger reason, cooldown remaining) SHALL be queryable through the API and visible on the dashboard.
Requirement 7: Adaptive Market Response
User Story: As a developer, I want the system to react to sudden market changes in real-time rather than waiting for the next scheduled cycle, so that positions are protected during volatile events.
Acceptance Criteria
- WHEN a new high-severity macro event (severity = high or critical) is classified by the existing macro classification pipeline, THE Trading_Engine SHALL trigger an immediate portfolio re-evaluation cycle outside the normal polling interval.
- WHEN an immediate re-evaluation is triggered, THE Trading_Engine SHALL re-check all open positions against updated stop-loss levels, tighten stops by a configurable factor (default: 0.5x normal ATR multiplier) for the duration of the event, and evaluate whether any positions should be closed.
- WHEN a tracked stock's price moves more than a configurable percentage (default: 5%) within a 15-minute window, THE Trading_Engine SHALL trigger an immediate re-evaluation for that specific position.
- WHILE a high-severity macro event is active (within its estimated_duration window), THE Trading_Engine SHALL increase the polling frequency for stop-loss checks from the default interval to a configurable fast interval (default: every 60 seconds).
- WHEN the Trading_Engine detects that multiple positions are simultaneously declining (more than 50% of open positions with negative unrealized P&L exceeding 2%), THE Trading_Engine SHALL reduce new position entries to zero and focus exclusively on managing existing positions until conditions stabilize.
Requirement 8: Portfolio Rebalancing
User Story: As a developer, I want the system to periodically rebalance the portfolio to avoid over-concentration in any single stock or sector, so that diversification is maintained automatically.
Acceptance Criteria
- THE Portfolio_Rebalancer SHALL run at a configurable interval (default: weekly, at market open on Monday) and evaluate the current portfolio against sector exposure limits and single-stock concentration limits defined by the active Risk_Tier.
- WHEN a single stock position exceeds the Risk_Tier's max_position_pct of the Active_Pool, THE Portfolio_Rebalancer SHALL generate a partial sell order to bring the position back within limits.
- WHEN a sector's total exposure exceeds the Risk_Tier's max_sector_pct of the Active_Pool, THE Portfolio_Rebalancer SHALL generate sell orders for the lowest-confidence positions in that sector to bring exposure within limits.
- THE Portfolio_Rebalancer SHALL enforce a configurable maximum number of open positions (default: 10) and prevent new entries when the limit is reached, prioritizing higher-confidence opportunities over existing lower-confidence positions.
- WHEN the Portfolio_Rebalancer generates rebalancing orders, THE Portfolio_Rebalancer SHALL submit them through the normal Broker_Service queue with a
rebalancetag in the decision trace, and persist the rebalancing rationale in PostgreSQL. - THE Portfolio_Rebalancer SHALL respect the Trading_Window constraints and Circuit_Breaker status — rebalancing orders are not submitted outside market hours or when a circuit breaker is active.
Requirement 9: Sector Diversification and Correlation Awareness
User Story: As a developer, I want the system to enforce diversification rules so that the portfolio is not over-exposed to a single sector or to stocks that move together.
Acceptance Criteria
- THE Position_Sizer SHALL maintain a Correlation_Matrix computed from the trailing 90-day price history of all tracked companies, refreshed daily.
- WHEN the Position_Sizer evaluates a new trade, THE Position_Sizer SHALL compute the weighted average correlation between the candidate stock and all existing portfolio positions, and reduce the allocation proportionally when the average correlation exceeds 0.5.
- WHEN the weighted average correlation between a candidate stock and the existing portfolio exceeds 0.8, THE Position_Sizer SHALL reject the trade entirely and log the rejection reason.
- THE Position_Sizer SHALL track sector exposure as the sum of market values of all positions in each sector, using the sector field from the companies table.
- WHEN the portfolio holds positions in fewer than 3 sectors, THE Position_Sizer SHALL apply a diversification bonus (1.2x allocation multiplier) to trades in under-represented sectors to encourage diversification.
Requirement 10: Earnings Calendar Awareness
User Story: As a developer, I want the system to reduce risk around earnings announcements because earnings are high-volatility events that can move stocks unpredictably.
Acceptance Criteria
- THE Trading_Engine SHALL maintain an Earnings_Calendar table in PostgreSQL containing the next known earnings date for each tracked company, populated from market data or manual entry.
- WHEN a tracked company's earnings date is within a configurable pre-earnings window (default: 3 trading days), THE Position_Sizer SHALL reduce the maximum position size for that company by 50% and THE Stop_Loss_Manager SHALL tighten stop-losses by a configurable factor (default: 0.7x normal ATR multiplier).
- WHEN a tracked company's earnings date is within 1 trading day, THE Trading_Engine SHALL not open new positions in that company and SHALL flag existing positions for manual review via a dashboard alert.
- WHEN a tracked company reports earnings and the result is reflected in the next recommendation cycle, THE Trading_Engine SHALL resume normal position sizing for that company after a configurable post-earnings cooldown (default: 1 trading day).
Requirement 11: Trading Window and Gradual Entry
User Story: As a developer, I want the system to avoid trading during the volatile open and close periods and to scale into positions gradually rather than all at once.
Acceptance Criteria
- THE Trading_Engine SHALL only submit new orders during the Trading_Window: market hours excluding the first 15 minutes after open (9:45 AM ET) and the last 15 minutes before close (3:45 PM ET).
- WHEN the Trading_Engine is outside the Trading_Window, THE Trading_Engine SHALL queue pending decisions and execute them when the window reopens, unless the recommendation has expired or conditions have changed.
- WHEN the Position_Sizer computes a position size exceeding a configurable gradual entry threshold (default: $30 or 5% of Active_Pool, whichever is smaller), THE Trading_Engine SHALL split the order into multiple tranches (default: 3 tranches) submitted at configurable intervals (default: 15 minutes apart).
- WHEN executing a Gradual_Entry, THE Trading_Engine SHALL re-evaluate the recommendation confidence and price conditions before submitting each subsequent tranche, and cancel remaining tranches if conditions have deteriorated.
- WHEN executing a Gradual_Entry, THE Trading_Engine SHALL link all tranches to the same parent decision record so that the full entry sequence is traceable.
Requirement 12: Tax-Loss Harvesting Awareness
User Story: As a developer, I want the system to track cost basis and flag wash sale risks so that I have visibility into tax implications even during paper trading.
Acceptance Criteria
- THE Trading_Engine SHALL maintain Tax_Lot records in PostgreSQL for every position entry, recording the acquisition date, quantity, cost basis per share, and current status (open, closed, washed).
- WHEN the Trading_Engine closes a position at a loss, THE Trading_Engine SHALL check whether the same ticker was purchased within the preceding 30 days or will be purchased within the following 30 days (based on pending recommendations), and flag the trade as a potential wash sale.
- WHEN a potential wash sale is detected, THE Trading_Engine SHALL log the event, tag the Tax_Lot record, and include the wash sale flag in the trade's decision trace.
- THE Performance_Tracker SHALL compute realized gains and losses using the Tax_Lot cost basis (FIFO method) and include a tax-adjusted P&L alongside the raw P&L in portfolio metrics.
Requirement 13: Portfolio Heat Management
User Story: As a developer, I want the system to limit the total risk across all positions so that even if every stop-loss is hit simultaneously, the portfolio loss is bounded.
Acceptance Criteria
- THE Position_Sizer SHALL compute Portfolio_Heat as the sum across all open positions of:
position_value * (entry_price - stop_loss_price) / entry_price. - WHEN the current Portfolio_Heat exceeds the Risk_Tier's max_portfolio_heat percentage of the Active_Pool, THE Position_Sizer SHALL reject new position entries until existing positions are closed or stop-losses are tightened to reduce heat.
- WHEN the Portfolio_Heat exceeds 80% of the max_portfolio_heat threshold, THE Stop_Loss_Manager SHALL proactively tighten stop-losses on the lowest-confidence positions to reduce overall heat.
- THE Portfolio_Heat value SHALL be computed and persisted at every decision loop iteration and be queryable through the API and visible on the dashboard.
Requirement 14: Performance Tracking and Metrics
User Story: As a developer, I want real-time performance metrics and dashboards so that I can see how the autonomous engine is performing at a glance.
Acceptance Criteria
- THE Performance_Tracker SHALL compute and persist the following metrics at a configurable interval (default: every 5 minutes during market hours): total portfolio value, Active_Pool value, Reserve_Pool balance, unrealized P&L, realized P&L, daily P&L, win count, loss count, win rate, average win amount, average loss amount, profit factor, Sharpe ratio (annualized, using daily returns over trailing 30 days), max drawdown (from peak portfolio value), and current drawdown percentage.
- THE Performance_Tracker SHALL compute per-trade metrics for every closed position: entry price, exit price, hold duration, P&L amount, P&L percentage, and the recommendation ID that triggered the trade.
- THE Performance_Tracker SHALL persist daily portfolio snapshots in PostgreSQL containing end-of-day portfolio value, daily return, cumulative return, and all positions with their unrealized P&L.
- THE Dashboard SHALL display a trading engine overview panel showing: current Risk_Tier, Circuit_Breaker status, Active_Pool and Reserve_Pool balances, Portfolio_Heat gauge, and the last 24 hours of P&L.
- THE Dashboard SHALL display a portfolio composition panel showing: current positions with entry price, current price, unrealized P&L, stop-loss level, take-profit level, and sector allocation pie chart.
- THE Dashboard SHALL display a trade history panel showing: completed trades with entry/exit prices, P&L, hold duration, and the recommendation thesis that triggered each trade.
- THE Dashboard SHALL display a performance chart panel showing: cumulative P&L over time, daily returns bar chart, and drawdown chart, using the existing Recharts library.
Requirement 15: Backtesting
User Story: As a developer, I want to backtest the trading strategy against historical data already in the database before risking real money, so that I can validate the approach.
Acceptance Criteria
- THE Backtester SHALL accept a date range, initial capital amount, and Risk_Tier configuration as inputs, and replay historical recommendations from the recommendations table within that date range.
- WHEN replaying historical recommendations, THE Backtester SHALL simulate the Trading_Engine's decision logic (position sizing, stop-loss/take-profit, circuit breakers, reserve pool, rebalancing) using historical price data from the market data tables.
- THE Backtester SHALL produce the same set of metrics as the Performance_Tracker (total return, Sharpe ratio, max drawdown, win rate, profit factor, trade count) for the simulated period.
- THE Backtester SHALL persist backtest results in PostgreSQL with a unique backtest_id, the configuration used, and the full trade log, so that results can be compared across different configurations.
- THE Backtester SHALL be invocable through the API at
POST /api/trading/backtestwith the date range, capital, and risk tier parameters, and return the backtest_id for result retrieval. - THE Dashboard SHALL display a backtesting panel where the operator can configure and launch backtests, and view results including the equity curve, trade log, and summary metrics.
Requirement 16: Trading Engine Configuration and Control
User Story: As a developer, I want to configure, start, stop, and monitor the trading engine through the API and dashboard, so that I have full control over autonomous operation.
Acceptance Criteria
- THE Trading_Engine SHALL be configurable through a trading_engine_config table in PostgreSQL containing: enabled (boolean), risk_tier (conservative/moderate/aggressive), reserve_siphon_pct, polling_interval_seconds, gradual_entry_tranches, and all circuit breaker thresholds.
- THE API SHALL expose a
GET /api/trading/statusendpoint returning the current engine state: enabled/disabled, active Risk_Tier, Circuit_Breaker status, Active_Pool balance, Reserve_Pool balance, Portfolio_Heat, open position count, and last decision timestamp. - THE API SHALL expose a
PUT /api/trading/configendpoint allowing operators to update engine configuration, with changes taking effect on the next decision loop iteration. - THE API SHALL expose a
POST /api/trading/pauseandPOST /api/trading/resumeendpoint to temporarily halt and resume autonomous trading without changing the enabled configuration. - THE Dashboard SHALL display a trading engine control panel with start/pause/resume controls, Risk_Tier selector, and real-time engine status indicators.
- WHEN the Trading_Engine configuration changes, THE Trading_Engine SHALL record an audit event with the previous configuration, new configuration, and the source of the change (operator or auto-adjustment).
Requirement 17: Decision Audit Trail
User Story: As a developer, I want a complete audit trail of every decision the trading engine makes, so that I can understand why it took or skipped every trade.
Acceptance Criteria
- WHEN the Trading_Engine evaluates a recommendation, THE Trading_Engine SHALL persist a trading_decision record containing: recommendation_id, decision (act or skip), skip_reason (if skipped), computed_position_size, risk_tier_at_decision, portfolio_heat_at_decision, active_pool_at_decision, reserve_pool_at_decision, circuit_breaker_status, correlation_check_result, sector_exposure_check_result, earnings_proximity_flag, and timestamp.
- WHEN the Trading_Engine submits an order, THE Trading_Engine SHALL include the trading_decision_id in the order job payload so that the existing Broker_Service decision_trace links back to the autonomous engine's reasoning.
- THE API SHALL expose a
GET /api/trading/decisionsendpoint returning recent trading decisions with pagination, filterable by ticker, decision type (act/skip), and date range. - THE Dashboard SHALL display a decision log panel showing recent decisions with expandable detail showing the full reasoning chain from recommendation through position sizing through execution.
Requirement 18: Trading Engine Storage
User Story: As a data engineer, I want all trading engine state persisted in PostgreSQL with appropriate schemas, so that the engine can recover from restarts and data is available for analysis.
Acceptance Criteria
- THE System SHALL create a database migration adding tables for: trading_engine_config, reserve_pool_ledger, risk_tier_history, circuit_breaker_events, trading_decisions, position_stop_levels, portfolio_snapshots, backtest_runs, backtest_trades, tax_lots, earnings_calendar, and correlation_matrix_cache.
- THE reserve_pool_ledger table SHALL record every deposit and withdrawal with amount, balance_after, trigger (profit_siphon, emergency_liquidation, manual_adjustment), and timestamp.
- THE position_stop_levels table SHALL record every stop-loss and take-profit level and adjustment for every open position, with the computation inputs (ATR value, multiplier, signal confidence) for reproducibility.
- THE portfolio_snapshots table SHALL store daily end-of-day snapshots with portfolio value, active pool, reserve pool, positions JSON, and all computed metrics.
- WHEN the Trading_Engine restarts, THE Trading_Engine SHALL reconstruct its state from PostgreSQL (open positions, reserve pool balance, active risk tier, circuit breaker status) and resume operation without data loss.
Requirement 19: Notification System
User Story: As a developer who is not watching the dashboard all day, I want the system to send me text messages and emails for critical events, so that I know immediately when something important happens.
Acceptance Criteria
- THE Notification_Service SHALL support two delivery channels: SMS via AWS SNS and email via the Gmail API, each independently configurable and toggleable.
- THE Notification_Service SHALL send an immediate notification WHEN any of the following events occur: a Circuit_Breaker is triggered, a Circuit_Breaker cooldown expires and trading resumes, the Risk_Tier_Controller changes the active Risk_Tier, the Reserve_Pool receives an emergency liquidation, or a single trade P&L exceeds a configurable threshold (default: 5% of Active_Pool).
- THE Notification_Service SHALL send a daily performance summary notification at a configurable time (default: 30 minutes after market close) containing: daily P&L, total portfolio value, Active_Pool and Reserve_Pool balances, number of trades executed, current Risk_Tier, and any open circuit breaker status.
- THE Notification_Service SHALL send a weekly performance digest containing: weekly P&L, win/loss count, Sharpe ratio, max drawdown, top winning and losing trades, and Risk_Tier changes during the week.
- WHEN configuring SMS notifications, THE Notification_Service SHALL use AWS SNS with a configurable SNS topic ARN and phone number, authenticating via AWS credentials (access key and secret key) stored as environment variables or Kubernetes secrets.
- WHEN configuring email notifications, THE Notification_Service SHALL use the Gmail API with OAuth2 credentials (client ID, client secret, refresh token) stored as environment variables or Kubernetes secrets, sending from a configurable sender address to a configurable recipient address.
- THE Notification_Service SHALL implement rate limiting (default: maximum 10 SMS and 20 emails per hour) to prevent notification storms during volatile market conditions.
- THE Notification_Service SHALL persist all sent notifications in PostgreSQL with the channel, event type, message content, delivery status, and timestamp for audit purposes.
- THE API SHALL expose a
GET /api/trading/notifications/configandPUT /api/trading/notifications/configendpoint for viewing and updating notification preferences (channels enabled, phone number, email address, event types, rate limits). - THE Dashboard SHALL display a notification preferences panel where the operator can configure which events trigger notifications, select delivery channels, and view recent notification history.
- IF a notification delivery fails (SNS publish error or Gmail API error), THEN THE Notification_Service SHALL retry up to 3 times with exponential backoff and log the failure, but SHALL NOT block or delay trading operations.
Requirement 20: Micro-Trading Mode
User Story: As a developer, I want the option to enable faster trading cycles that evaluate short-term signals on 5-minute and 15-minute intervals, so that the engine can capture intraday opportunities without being limited to daily recommendation cycles.
Acceptance Criteria
- THE Trading_Engine SHALL support an optional Micro_Trading_Mode that, when enabled, polls for intraday trend window signals (intraday and 1d windows) at a configurable fast interval (default: every 5 minutes during market hours) in addition to the standard recommendation polling.
- WHEN Micro_Trading_Mode is enabled, THE Trading_Engine SHALL evaluate intraday trend summaries from the Aggregation_Engine and generate micro-trade decisions for signals that meet the active Risk_Tier's confidence threshold.
- WHEN Micro_Trading_Mode generates a trade, THE Position_Sizer SHALL apply a configurable micro-trade allocation cap (default: 3% of Active_Pool per micro-trade) that is lower than the standard position sizing cap, limiting the risk of any single short-term trade.
- WHEN Micro_Trading_Mode is enabled, THE Trading_Engine SHALL enforce a configurable maximum number of micro-trades per day (default: 10) to prevent excessive trading and commission accumulation.
- WHEN Micro_Trading_Mode is enabled, THE Stop_Loss_Manager SHALL use tighter stop-loss and take-profit levels for micro-trade positions: stop-loss at 1.0x ATR (instead of the standard tier multiplier) and take-profit at 1.5x the stop distance.
- WHEN a micro-trade position has been open for longer than a configurable maximum hold duration (default: 2 hours), THE Trading_Engine SHALL close the position at market price regardless of P&L, to prevent short-term trades from becoming unintended long-term holds.
- THE Trading_Engine SHALL track micro-trade performance metrics separately from standard trade metrics, including: micro-trade win rate, average micro-trade P&L, micro-trade count per day, and micro-trade contribution to total portfolio P&L.
- THE Micro_Trading_Mode SHALL be toggleable through the trading_engine_config table and the API, independently of the main Trading_Engine enabled state.
- THE Dashboard SHALL display a micro-trading panel showing: micro-trade mode status (enabled/disabled), today's micro-trade count and P&L, active micro-trade positions, and micro-trade performance metrics over the trailing 7 days.
- WHEN Micro_Trading_Mode is enabled, THE Trading_Engine SHALL respect all existing constraints (Trading_Window, Circuit_Breakers, Portfolio_Heat limits, correlation checks) and apply them to micro-trades with the same rigor as standard trades.