# 02-ANALISIS - Frontend Module Documentation

**Tarea:** TASK-2026-01-25-FRONTEND-MODULE-DOCS
**Fase CAPVED:** A - Análisis
**Fecha:** 2026-01-25
**Responsable:** Claude Opus 4.5

---

## RESUMEN EJECUTIVO

Se analizaron los 8 módulos frontend de trading-platform usando 8 agentes Explore en paralelo. El análisis revela una arquitectura modular consistente con patrones de diseño uniformes.

**Estado:** ✅ Análisis completado
**Módulos analizados:** 8/8 (100%)
**Tiempo de ejecución:** ~5 minutos (paralelo)

---

## 1. HALLAZGOS POR MÓDULO

### 1.1 Auth Module (OQI-001)

**Ubicación:** `apps/frontend/src/modules/auth/`

**Estructura encontrada:**
- **Páginas (6):** Login, Register, ForgotPassword, ResetPassword, VerifyEmail, AuthCallback, SecuritySettings
- **Componentes (4):** PhoneLoginForm, SocialLoginButtons, DeviceCard, SessionsList
- **Hooks:** No encontrados en el módulo (probablemente en shared)
- **Services:** Integrado con authStore (Zustand)
- **Store:** `stores/authStore.ts` (JWT, session management)

**APIs Consumidas:**
- POST `/auth/login` - Autenticación
- POST `/auth/register` - Registro
- POST `/auth/forgot-password` - Recuperación
- POST `/auth/reset-password` - Reset de contraseña
- GET `/auth/verify-email` - Verificación email
- GET `/auth/session` - Validación de sesión
- POST `/auth/logout` - Cierre de sesión

**Características especiales:**
- Social login (Google, Facebook, Apple)
- Phone authentication
- Device tracking y gestión de sesiones
- Security settings management

---

### 1.2 Education Module (OQI-002)

**Ubicación:** `apps/frontend/src/modules/education/`

**Estructura encontrada:**
- **Páginas (6):** Courses, CourseDetail, MyLearning, Lesson, Quiz, Leaderboard
- **Componentes (13):** VideoProgressPlayer, CourseProgressTracker, XPProgress, StreakCounter, AchievementBadge, LeaderboardTable, LessonNotes, CourseReviews, RecommendedCourses, VideoUploadForm, CreatorDashboard, CertificateGenerator, LiveStreamPlayer
- **Hooks:** No custom hooks (usa educationStore)
- **Services:** `education.service.ts` (38 endpoints)
- **Store:** `educationStore.ts` (cursos, quizzes, gamificación)
- **Types:** `education.types.ts` (completo)

**APIs Consumidas (38 endpoints):**
- Categorías (2): GET/POST `/education/categories`
- Cursos (6): GET/POST `/education/courses`, `/courses/:id`, `/courses/slug/:slug`
- Lecciones (4): GET/POST `/education/lessons/:id`
- Enrollments (4): GET/POST `/education/my/enrollments`
- Quizzes (9): GET/POST `/education/quizzes`, attempts, results
- Gamificación (9): GET/POST `/education/gamification/*`
- Admin (8+): POST `/education/courses`, modules, lessons

**Características especiales:**
- Sistema de gamificación (XP, streaks, achievements, leaderboard)
- Video player con bookmarks y notas
- Quiz system con time limits
- Creator dashboard con analytics
- Live streaming support

---

### 1.3 Trading Module (OQI-003)

**Ubicación:** `apps/frontend/src/modules/trading/`

**Estructura encontrada:**
- **Páginas (1):** Trading (dashboard principal multi-panel)
- **Componentes (38):** CandlestickChartWithML, WatchlistSidebar, OrderForm, PaperTradingPanel, MLSignalsPanel, MT4ConnectionStatus, RiskMonitor, AdvancedOrderEntry, TradingScreener, MarketDepthPanel, etc.
- **Hooks (1):** `useMT4WebSocket` (WebSocket para MT4)
- **Services (2):** `trading.service.ts` (API principal), `mlService.ts` (ML Engine)
- **Store:** `tradingStore.ts` (market data, paper trading, watchlist)
- **Types:** `trading.types.ts`

**APIs Consumidas (50+ endpoints):**
- Market Data: GET `/trading/market/*` (klines, price, ticker, orderbook)
- Indicators: GET `/trading/indicators/:symbol/*` (SMA, EMA, RSI, MACD, Bollinger)
- Watchlists: GET/POST/DELETE `/trading/watchlists/*`
- Paper Trading: GET/POST `/trading/paper/*` (orders, positions, balances)
- Alerts: GET/POST/DELETE `/trading/alerts/*`
- ML Engine: POST `http://localhost:3083/api/*` (signals, ICT, ensemble, scan)
- LLM Agent: POST `http://localhost:3085/api/*` (MT4 integration)

**Características especiales:**
- ML-powered predictions con ICT/SMC analysis
- Paper trading sandbox
- Real MT4 integration via WebSocket
- Advanced charting con lightweight-charts
- Risk monitoring en tiempo real

---

### 1.4 Investment Module (OQI-004)

**Ubicación:** `apps/frontend/src/modules/investment/`

**Estructura encontrada:**
- **Páginas (8):** Investment, Portfolio, AccountDetail, Products, ProductDetail, Reports, Transactions, Withdrawals
- **Componentes (6):** AccountSummaryCard, PerformanceWidgetChart, ProductComparisonTable, AccountSettingsPanel, DepositForm, WithdrawForm
- **Hooks (2):** `useMLAnalysis`, `useQuickSignals`
- **Services:** `investment.service.ts` (17 endpoints)
- **Store:** `portfolioStore.ts` (con WebSocket)
- **Types:** `investment.types.ts`

**APIs Consumidas (17 endpoints):**
- Products: GET `/investment/products`, `/products/:id`, `/products/:id/performance`
- Accounts: GET/POST `/investment/accounts`, `/accounts/:id`, `/accounts/:id/close`
- Transactions: GET/POST `/investment/accounts/:id/transactions`, `/deposit`, `/withdraw`
- Distributions: GET `/investment/accounts/:id/distributions`
- Withdrawals: GET `/investment/withdrawals`

**Características especiales:**
- 3 trading agents (Atlas, Orion, Nova) con perfiles de riesgo
- Stripe integration para deposits
- Dual withdrawal (bank transfer + crypto)
- Real-time portfolio tracking via WebSocket
- Performance analytics con export

---

### 1.5 Payments Module (OQI-005)

**Ubicación:** `apps/frontend/src/modules/payments/`

**Estructura encontrada:**
- **Páginas (4):** Pricing, Billing, CheckoutSuccess, CheckoutCancel
- **Componentes (15):** PricingCard, SubscriptionCard, WalletCard, UsageProgress, PaymentMethodForm, InvoiceList, TransactionHistory, etc.
- **Hooks:** Ninguno (usa paymentStore directamente)
- **Services:** `payment.service.ts` (27 endpoints)
- **Store:** `paymentStore.ts` (subscriptions, wallet, invoices)
- **Types:** `payment.types.ts`

**APIs Consumidas (27 endpoints):**
- Plans: GET `/payments/plans`, `/plans/:slug`
- Subscriptions: GET/POST `/payments/subscription`, `/subscription/cancel`, `/subscription/change-plan`
- Checkout: POST `/payments/checkout`, `/payments/billing-portal`
- Payment Methods: GET/POST/DELETE `/payments/methods`
- Invoices: GET `/payments/invoices`, `/invoices/:id/pdf`
- Wallet: GET/POST `/payments/wallet`, `/wallet/transactions`, `/wallet/deposit`, `/wallet/withdraw`
- Coupons: POST `/payments/coupons/validate`
- Billing Info: GET/PUT `/payments/billing-info`
- Usage: GET `/payments/usage`

**Características especiales:**
- Stripe integration completa
- Plan management (free/basic/pro/premium/enterprise)
- Wallet system con deposits/withdrawals
- Usage tracking y limits enforcement
- Prorated pricing para cambios de plan

---

### 1.6 ML Module (OQI-006)

**Ubicación:** `apps/frontend/src/modules/ml/`

**Estructura encontrada:**
- **Páginas (1):** MLDashboard (tabs: Signals, ICT Analysis, Ensemble)
- **Componentes (12):** AMDPhaseIndicator, PredictionCard, SignalsTimeline, AccuracyMetrics, ICTAnalysisCard, EnsembleSignalCard, TradeExecutionModal, ConfidenceMeter (NEW), SignalPerformanceTracker (NEW), ModelAccuracyDashboard (NEW), BacktestResultsVisualization (NEW)
- **Hooks (2):** `useMLAnalysis` (con caché de 1 minuto), `useQuickSignals`
- **Services:** `mlService.ts` (11 endpoints en port 3083)
- **Store:** NO (usa hooks directamente)
- **Types:** `ml.types.ts`
- **README:** ✅ YA EXISTE (pero necesita actualización con 4 componentes nuevos)

**APIs Consumidas (11 endpoints):**
- Signals: GET/POST `/api/v1/signals/latest/:symbol`, `/signals/active`, `/signals/generate`
- AMD: GET `/api/v1/amd/detect/:symbol`
- Range: GET `/api/v1/predict/range/:symbol`
- Backtest: POST `/api/v1/backtest/run`
- ICT: POST `/api/ict/:symbol`
- Ensemble: POST/GET `/api/ensemble/:symbol`, `/ensemble/quick/:symbol`
- Scan: POST `/api/scan`
- Health: GET `/health`

**Características especiales:**
- ML Engine en puerto 3083 (FastAPI)
- AMD Phase detection (Accumulation/Manipulation/Distribution)
- ICT/SMC analysis (Order Blocks, Fair Value Gaps)
- Ensemble signals (multi-model voting)
- Backtesting con performance metrics
- Auto-refresh cada 60 segundos
- Cache inteligente de 1 minuto

---

### 1.7 Assistant Module (OQI-007)

**Ubicación:** `apps/frontend/src/modules/assistant/`

**Estructura encontrada:**
- **Páginas (1):** Assistant (LLM copilot interface)
- **Componentes (18):** ChatMessage, ChatInput, SignalCard, ConversationHistory, ContextPanel, ChatHeader, MessageList, MessageSearch, MarkdownRenderer, ToolCallCard, MessageFeedback, StreamingIndicator, AssistantSettingsPanel, SignalExecutionPanel, AnalysisRequestForm (NEW OQI-007), StrategyTemplateSelector (NEW), LLMConfigPanel (NEW), ContextMemoryDisplay (NEW)
- **Hooks (2):** `useChatAssistant` (chat logic), `useStreamingChat` (SSE streaming)
- **Services (2):** `chat.service.ts` (port 3000), `llmAgentService.ts` (port 3085)
- **Store:** `chatStore.ts` (sessions, messages, persistence)
- **Types:** `chat.types.ts`

**APIs Consumidas (6 + LLM Agent):**
- Chat API (port 3000): GET/POST/DELETE `/api/v1/llm/sessions`, `/sessions/:id/chat`, GET `/analyze/:symbol`
- LLM Agent (port 3085): POST predictions, backtesting; GET risk summary, active signals

**Características especiales:**
- Claude models (3.5 Sonnet/Opus/Haiku) integration
- Server-Sent Events (SSE) streaming
- Conversation history con persistence
- Tool calls visualization
- Trading signal generation via LLM
- Context memory con checkpoints
- Message feedback system

---

### 1.8 Portfolio Module (OQI-008)

**Ubicación:** `apps/frontend/src/modules/portfolio/`

**Estructura encontrada:**
- **Páginas (4):** PortfolioDashboard, CreatePortfolio, EditAllocations, CreateGoal
- **Componentes (5):** AllocationChart (SVG donut), AllocationTable, GoalCard, PerformanceChart (Canvas), RebalanceCard
- **Hooks:** Ninguno (usa portfolioStore)
- **Services:** `portfolio.service.ts` (13 endpoints)
- **Store:** `portfolioStore.ts` (con WebSocket)
- **Types:** Definidos en portfolio.service.ts

**APIs Consumidas (13 endpoints):**
- Portfolio: GET/POST `/api/v1/portfolio`, `/portfolio/:id`, PUT `/portfolio/:id/allocations`
- Rebalance: GET/POST `/api/v1/portfolio/:id/rebalance`
- Stats: GET `/api/v1/portfolio/:id/stats`
- Performance: GET `/api/v1/portfolio/:id/performance?period=`
- Goals: GET/POST/PUT/DELETE `/api/v1/portfolio/goals`

**Características especiales:**
- 10 crypto assets soportados (BTC, ETH, USDT, SOL, LINK, AVAX, ADA, DOT, MATIC, UNI)
- 3 risk profiles (Conservative, Moderate, Aggressive)
- Real-time updates via WebSocket
- Canvas-based custom charts (no libraries)
- Goal tracking con progress monitoring
- AI-powered rebalancing recommendations

---

## 2. ANÁLISIS COMPARATIVO

### 2.1 Patrones Arquitectónicos Comunes

| Patrón | Módulos que lo usan |
|--------|---------------------|
| **Zustand Store** | auth, education, trading, payments, portfolio, assistant (chatStore) |
| **Service Layer (Axios)** | Todos (8/8) |
| **TypeScript Types** | Todos (8/8) |
| **Pages + Components** | Todos (8/8) |
| **Custom Hooks** | trading (1), investment (2), ml (2), assistant (2) |
| **WebSocket** | investment (portfolioStore), portfolio, trading (useMT4WebSocket) |
| **Real-time Updates** | trading, investment, portfolio, assistant (SSE) |

### 2.2 Complejidad por Módulo

| Módulo | Páginas | Componentes | Hooks | Endpoints | Complejidad |
|--------|---------|-------------|-------|-----------|-------------|
| **trading** | 1 | 38 | 1 | 50+ | ⭐⭐⭐⭐⭐ Muy alta |
| **education** | 6 | 13 | 0 | 38 | ⭐⭐⭐⭐ Alta |
| **assistant** | 1 | 18 | 2 | 6+ | ⭐⭐⭐⭐ Alta |
| **payments** | 4 | 15 | 0 | 27 | ⭐⭐⭐ Media-alta |
| **ml** | 1 | 12 | 2 | 11 | ⭐⭐⭐ Media |
| **investment** | 8 | 6 | 2 | 17 | ⭐⭐⭐ Media |
| **auth** | 6 | 4 | 0 | 7 | ⭐⭐ Baja-media |
| **portfolio** | 4 | 5 | 0 | 13 | ⭐⭐ Baja-media |

### 2.3 Tecnologías Especiales por Módulo

- **trading:** lightweight-charts, WebSocket MT4, ML Engine integration
- **education:** Video player avanzado, gamification system, live streaming
- **payments:** Stripe integration, wallet system
- **investment:** Stripe deposits, bank/crypto withdrawals
- **ml:** FastAPI ML Engine (port 3083), backtesting
- **assistant:** Claude AI, SSE streaming, tool calls
- **portfolio:** Canvas charts (custom), WebSocket real-time
- **auth:** Social login, phone auth, device tracking

---

## 3. INVENTARIO DE APIs POR MÓDULO

### APIs Totales: ~190 endpoints

| Módulo | Base URL | Endpoints | Puerto |
|--------|----------|-----------|--------|
| auth | `/auth/*` | 7 | 3080 |
| education | `/education/*` | 38 | 3080 |
| trading | `/trading/*` + ML Engine | 50+ | 3080 + 3083 + 3085 |
| investment | `/investment/*` | 17 | 3080 |
| payments | `/payments/*` | 27 | 3080 |
| ml | ML Engine API | 11 | 3083 |
| assistant | `/api/v1/llm/*` + LLM Agent | 6+ | 3000 + 3085 |
| portfolio | `/portfolio/*` | 13 | 3080 |

---

## 4. HALLAZGOS CLAVE

### 4.1 Consistencia Arquitectónica ✅

- Todos los módulos siguen estructura pages/ + components/
- Service layer uniforme con Axios
- TypeScript types completos
- Zustand como state manager estándar

### 4.2 Módulos con README Existente

- **ml:** Ya tiene README.md pero necesita actualización con 4 componentes nuevos (ConfidenceMeter, SignalPerformanceTracker, ModelAccuracyDashboard, BacktestResultsVisualization)

### 4.3 Módulos Sin Custom Hooks

- auth, education, payments, portfolio → usan stores directamente
- trading, investment, ml, assistant → tienen hooks especializados

### 4.4 Integración de Servicios Externos

- **Stripe:** payments, investment
- **ML Engine (FastAPI):** ml, trading, investment, assistant
- **LLM Agent:** assistant, trading (MT4)
- **WebSocket:** trading, investment, portfolio

---

## 5. DATOS RECOPILADOS PARA READMEs

Toda la información necesaria ha sido recopilada:

✅ **auth:** 6 páginas, 4 componentes, 7 APIs
✅ **education:** 6 páginas, 13 componentes, 38 APIs, gamificación
✅ **trading:** 1 página, 38 componentes, 1 hook, 50+ APIs, ML integration
✅ **investment:** 8 páginas, 6 componentes, 2 hooks, 17 APIs, Stripe
✅ **payments:** 4 páginas, 15 componentes, 27 APIs, Stripe wallet
✅ **ml:** 1 página, 12 componentes, 2 hooks, 11 APIs, README a actualizar
✅ **assistant:** 1 página, 18 componentes, 2 hooks, 6+ APIs, Claude SSE
✅ **portfolio:** 4 páginas, 5 componentes, 13 APIs, WebSocket

---

## 6. PRÓXIMOS PASOS

**Fase P (Planeación):**
- Definir orden de creación de READMEs
- Validar template con un ejemplo
- Preparar contenido específico por módulo

**Estimación de esfuerzo:**
- 7 READMEs nuevos × 45 min = 5.25 horas
- 1 README actualización × 15 min = 0.25 horas
- **Total: 5.5 horas**

---

**Estado:** ✅ Fase A completada
**Siguiente fase:** P - Planeación
