Strategy Execution & Performance Metrics Implementation
Overview
This implementation adds comprehensive strategy execution tracking and performance metrics to the Predicta strategy automation system. Users can now:- Track all strategy executions with detailed logs (when triggered, market, outcome, price, P&L)
- Monitor performance metrics including win rate, ROI, total P&L
- Analyze execution history with a detailed table viewer
- Cache metrics for fast retrieval without recalculation
Architecture
Type Definitions (src/types/portfolio.ts)
StrategyExecutionLog
Tracks individual strategy execution events:
StrategyPerformanceMetrics
Aggregated performance statistics:
Services
strategyMetricsService (src/services/strategyMetricsService.ts)
Core Methods:
logExecution(userId, strategyId, executionData)- Record a new strategy executioncloseExecution(userId, strategyId, executionId, pnl, roi)- Mark execution as closed with P&LgetExecutionLogs(userId, strategyId, limit)- Retrieve execution historycalculateMetrics(userId, strategyId)- Calculate metrics from logs (real-time)cacheMetrics(userId, strategyId)- Store metrics in strategy document for fast readsgetCachedMetrics(userId, strategyId)- Read pre-computed metrics (no recalculation)formatMetrics(metrics)- Format metrics for display (win rate %, currency format, etc.)
Components
StrategyMetricsCard (src/components/automate/StrategyMetricsCard.tsx)
Displays key performance metrics for a strategy:
- Loading skeleton while fetching metrics
- “No execution data yet” state
- Color coding (green for profit, red for loss)
- Icons for trending up/down
- Progress bar for win rate visualization
ExecutionLogsViewer (src/components/automate/ExecutionLogsViewer.tsx)
Detailed execution history in a sheet modal with table:
- Click “Execution Logs” button to open sheet
- Sortable columns (date, trigger type, market, order type, etc.)
- Emoji badges for trigger reason (🤖 AI, ⏰ Scheduled, 📊 Threshold, 🎯 Target, 👤 Manual)
- Status badges (PENDING, EXECUTED, CLOSED)
- Color-coded P&L (green profit, red loss)
- Summary statistics at bottom
- Responsive table for mobile
Integration in StrategyList
Each strategy card now includes:- StrategyMetricsCard embedded below strategy details
- ExecutionLogsViewer button in footer (alongside Delete)
Usage Flows
Flow 1: Log a Strategy Execution
When a strategy triggers and executes a trade:Flow 2: Close an Execution and Record P&L
When the position is eventually closed/sold:Flow 3: Display Metrics
Metrics automatically display in the UI:Flow 4: Calculate Fresh Metrics (Manual)
For real-time calculation without cache:Flow 5: Cache Metrics (Background Job)
Periodically cache metrics for faster reads:Flow 6: Use Cached Metrics (Fast Read)
For performance-critical UI updates:Metrics Calculations
Win Rate
Total P&L
Average P&L
ROI Metrics
Best/Worst Trades
Capital Metrics
State Management
No Redux/Zustand needed - data flows directly from Firestore:- StrategyMetricsCard reads from Firestore via getCachedMetrics()
- Loading state shows skeleton while fetching
- Empty state shown if no data
- Auto-updates when component remounts
Performance Considerations
Optimization Strategies
- Caching: Pre-computed metrics cached in strategy doc
- Pagination: ExecutionLogsViewer loads max 100 logs, limit configurable
- Lazy Loading: Only recalculate on explicit action
- Cloud Functions: Cache metrics every 5 minutes with scheduler
Recommended Cloud Function
Error Handling
All service methods include try-catch and emit errors viaerrorEmitter:
STRATEGY_LOG_EXECUTION_ERROR- Failed to create execution logSTRATEGY_CLOSE_EXECUTION_ERROR- Failed to close/update executionSTRATEGY_FETCH_LOGS_ERROR- Failed to retrieve logsSTRATEGY_CALCULATE_METRICS_ERROR- Failed to calculate metricsSTRATEGY_CACHE_METRICS_ERROR- Failed to cache metricsSTRATEGY_GET_CACHED_METRICS_ERROR- Failed to read cached metrics
Future Enhancements
- Advanced Charting: Chart P&L over time using Recharts
- Strategy Comparison: Compare metrics across multiple strategies
- Benchmark Comparison: Compare against market baseline
- Export Metrics: Download execution history as CSV
- Webhook Integration: Send metrics to external analytics
- Notifications: Alert on milestone metrics (e.g., 90% win rate)
- A/B Testing: Compare performance of strategy variations
- Time Range Filtering: View metrics for specific date ranges
Files Changed
- ✅
src/types/portfolio.ts- Added StrategyExecutionLog, StrategyPerformanceMetrics types - ✅
src/services/strategyMetricsService.ts- New metrics service (300+ lines) - ✅
src/services/strategyService.ts- Added execution logging hooks - ✅
src/components/automate/StrategyMetricsCard.tsx- Metrics display (150 lines) - ✅
src/components/automate/ExecutionLogsViewer.tsx- Execution history viewer (230 lines) - ✅
src/components/automate/StrategyList.tsx- Integrated metrics & logs into cards
Testing Checklist
- Create a test strategy (market-specific or portfolio-level)
- Manually log an execution with
logStrategyExecution() - Verify execution appears in ExecutionLogsViewer table
- Close the execution with
closeStrategyExecution()and add P&L - Verify metrics appear in StrategyMetricsCard
- Check win rate calculation (should show 100% for 1 profitable trade)
- Check P&L and ROI display correctness
- Test with multiple executions to verify aggregation
- Test error handling (try invalid strategyId, etc.)
- Mobile responsiveness of ExecutionLogsViewer sheet
Integration Points
To fully activate this system, you’ll need to:-
In the execution engine (when strategy triggers):
-
In the settlement/close flow (when position is closed):
-
Optional: Cache metrics periodically (Cloud Function):