Skip to main content

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 execution
  • closeExecution(userId, strategyId, executionId, pnl, roi) - Mark execution as closed with P&L
  • getExecutionLogs(userId, strategyId, limit) - Retrieve execution history
  • calculateMetrics(userId, strategyId) - Calculate metrics from logs (real-time)
  • cacheMetrics(userId, strategyId) - Store metrics in strategy document for fast reads
  • getCachedMetrics(userId, strategyId) - Read pre-computed metrics (no recalculation)
  • formatMetrics(metrics) - Format metrics for display (win rate %, currency format, etc.)
Firestore Structure:

Components

StrategyMetricsCard (src/components/automate/StrategyMetricsCard.tsx)

Displays key performance metrics for a strategy:
Features:
  • 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:
Features:
  • 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:
  1. StrategyMetricsCard reads from Firestore via getCachedMetrics()
  2. Loading state shows skeleton while fetching
  3. Empty state shown if no data
  4. Auto-updates when component remounts

Performance Considerations

Optimization Strategies

  1. Caching: Pre-computed metrics cached in strategy doc
  2. Pagination: ExecutionLogsViewer loads max 100 logs, limit configurable
  3. Lazy Loading: Only recalculate on explicit action
  4. Cloud Functions: Cache metrics every 5 minutes with scheduler

Error Handling

All service methods include try-catch and emit errors via errorEmitter:
Error codes:
  • STRATEGY_LOG_EXECUTION_ERROR - Failed to create execution log
  • STRATEGY_CLOSE_EXECUTION_ERROR - Failed to close/update execution
  • STRATEGY_FETCH_LOGS_ERROR - Failed to retrieve logs
  • STRATEGY_CALCULATE_METRICS_ERROR - Failed to calculate metrics
  • STRATEGY_CACHE_METRICS_ERROR - Failed to cache metrics
  • STRATEGY_GET_CACHED_METRICS_ERROR - Failed to read cached metrics

Future Enhancements

  1. Advanced Charting: Chart P&L over time using Recharts
  2. Strategy Comparison: Compare metrics across multiple strategies
  3. Benchmark Comparison: Compare against market baseline
  4. Export Metrics: Download execution history as CSV
  5. Webhook Integration: Send metrics to external analytics
  6. Notifications: Alert on milestone metrics (e.g., 90% win rate)
  7. A/B Testing: Compare performance of strategy variations
  8. 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:
  1. In the execution engine (when strategy triggers):
  2. In the settlement/close flow (when position is closed):
  3. Optional: Cache metrics periodically (Cloud Function):
This ensures real-time tracking while maintaining performant reads from cache.