learning_ai_invt_trdg/docs/planned/API_DOCUMENTATION_GUIDE.md
Saravana Achu Mac 83bc3af260 docs: add comprehensive documentation for coding agents
Created detailed documentation files to guide coding agents in implementing
the fixes and improvements identified in the functionality review:

1. API_DOCUMENTATION_GUIDE.md
   - Complete API endpoint catalog
   - Authentication documentation
   - REST API endpoints (health, user, trading, orders, market data, research, backtesting, feature flags, admin)
   - WebSocket namespaces (/trading, /admin, /)
   - Error responses and error codes
   - Rate limiting recommendations
   - Request ID propagation
   - Deprecation policy
   - OpenAPI/Swagger generation guide
   - Documentation maintenance process

2. ARCHITECTURE_DOCUMENTATION.md
   - System overview and high-level architecture
   - Monorepo structure and directory layout
   - Backend architecture (component structure, data flow, trading loop)
   - Web architecture (component structure, data flow, UI architecture)
   - Mobile architecture (component structure, data flow)
   - Shared code architecture (shared modules, platform integration)
   - Data architecture (Cosmos DB containers, data flow)
   - Service boundaries (backend, platform-service, web, mobile responsibilities)
   - Integration points (backend ↔ platform-service, web ↔ backend, mobile ↔ backend, etc.)
   - Security architecture (authentication, authorization, tenant isolation)
   - Monitoring & observability (telemetry, logging)
   - Deployment architecture (Docker, environment variables)
   - Scalability considerations (horizontal scaling, WebSocket scaling)

3. TROUBLESHOOTING_GUIDE.md
   - Backend issues (won't start, health check failing, trading loop not running, orders not executing, reconciliation failures)
   - Web issues (won't load, authentication failing, WebSocket connection failing, data not updating)
   - Mobile issues (won't launch, authentication failing, WebSocket connection failing, data not updating)
   - Database issues (Cosmos DB connection failing, slow performance, data inconsistency)
   - Authentication issues (platform-service unreachable, JWT token invalid)
   - WebSocket issues (connection drops, not receiving events)
   - Performance issues (backend slow response times, web slow load times)
   - Deployment issues (Docker build failing, container won't start)
   - Escalation procedures (when to escalate, escalation steps, on-call contact, incident response)
   - Common error messages (backend, web, mobile)
   - Monitoring and alerts (key metrics, alert thresholds, monitoring tools)

4. ONBOARDING_GUIDE.md
   - Project overview (what is the trading dashboard, tech stack, key concepts)
   - Prerequisites (required software, required accounts, optional tools)
   - Development setup (clone repo, install dependencies, configure environment, verify setup)
   - Project structure (monorepo layout, key files)
   - Development workflow (starting development, making changes, commit message format, pushing changes)
   - Testing (backend tests, web tests, mobile tests, verification script)
   - Code review process (PR process, PR checklist, code review guidelines)
   - Common tasks (adding backend endpoint, adding web component, adding mobile screen, adding feature flag)
   - Resources (documentation, external documentation, tools)
   - Getting help (internal resources, common issues, asking questions)
   - Best practices
   - Next steps (first week, first month, ongoing)

These documentation files provide detailed guidance for coding agents to implement
the fixes and improvements identified in FUNCTIONALITY_REVIEW.md without needing
to understand the entire codebase from scratch.
2026-05-09 17:02:05 -07:00

14 KiB

API Documentation Guide

Purpose: Comprehensive guide for documenting the trading dashboard API endpoints for consumption by web, mobile, and external clients.

Target Audience: API consumers (web developers, mobile developers, external integrators), backend developers maintaining API contracts.


Overview

The trading dashboard backend exposes REST APIs and WebSocket endpoints for trading operations, state management, and administrative controls. This guide provides a structured approach to documenting all API endpoints.


Current API Documentation State

Existing Documentation

  • BACKEND_API_DEPRECATION.md - Lists deprecated endpoints and migration paths
  • docs/BACKEND_AUDIT_SCHEMA.md - Documents audit event schema
  • docs/BACKEND_LEGACY_SUPABASE_SCRIPTS.md - Documents legacy Supabase script usage

Documentation Gaps

  • No comprehensive API endpoint catalog
  • No OpenAPI/Swagger specification
  • No request/response examples
  • No authentication documentation
  • No error response documentation
  • No rate limiting documentation
  • No WebSocket namespace documentation

API Documentation Structure

Create a comprehensive API documentation file: docs/API_REFERENCE.md

# Trading Dashboard API Reference

## Table of Contents
- Authentication
- REST API Endpoints
  - Health & Diagnostics
  - User & Profile
  - Trading Control
  - Orders & Positions
  - Trade History
  - Market Data
  - Research & Screener
  - Backtesting
  - Feature Flags
  - Admin Operations
- WebSocket Namespaces
  - /trading (user-scoped)
  - /admin (admin-only)
  - / (root, backward-compatible)
- Error Responses
- Rate Limiting
- Deprecation Policy

Authentication Documentation

Authentication Methods

Platform JWT (Recommended for Production)

# Request header
Authorization: Bearer <platform-jwt-token>

Legacy JWT (Local Development Only)

# Request header
Authorization: Bearer <legacy-jwt-token>

Token Validation

Backend validates JWT tokens using:

  • Platform public key (production)
  • Platform JWKS URL (production)
  • JWT_SECRET (local development)

Authentication Endpoints

GET /api/me/profile

  • Purpose: Get authenticated user profile
  • Authentication: Required
  • Response: User profile with role, permissions, tenant info

POST /api/auth/login (if legacy auth is enabled)

  • Purpose: Authenticate user
  • Request Body: { email, password }
  • Response: JWT token

REST API Endpoints

Health & Diagnostics

GET /health/live

  • Purpose: Liveness probe
  • Authentication: None
  • Response: { status: "ok", service: "trading-backend" }
  • Usage: Docker healthcheck, monitoring

GET /health/ready

  • Purpose: Readiness probe
  • Authentication: None
  • Response: { status: "ready", checks: {...} }
  • Usage: Kubernetes readiness probe

GET /api/health/dependencies

  • Purpose: Check external dependencies
  • Authentication: Required (admin role)
  • Response: Dependency health status

User & Profile

GET /api/me/profile

  • Purpose: Get authenticated user profile
  • Authentication: Required
  • Response:
{
  "userId": "string",
  "email": "string",
  "role": "admin" | "user",
  "tenantId": "string",
  "permissions": ["string"]
}

GET /api/users/:userId/profile

  • Purpose: Get user profile (admin only)
  • Authentication: Required (admin role)
  • Response: User profile

PUT /api/users/:userId/profile

  • Purpose: Update user profile (admin only)
  • Authentication: Required (admin role)
  • Request Body: Profile update

Trading Control

GET /api/trading/control

  • Purpose: Get global trading control state
  • Authentication: Required
  • Response:
{
  "globalTradingEnabled": boolean,
  "pausedAt": "timestamp | null",
  "pausedBy": "string | null",
  "pausedReason": "string | null"
}

POST /api/trading/pause

  • Purpose: Pause global trading
  • Authentication: Required (admin role)
  • Request Body:
{
  "reason": "string"
}

POST /api/trading/resume

  • Purpose: Resume global trading
  • Authentication: Required (admin role)
  • Request Body: None

POST /api/trading/pause/profile/:profileId

  • Purpose: Pause specific trading profile
  • Authentication: Required
  • Request Body:
{
  "reason": "string"
}

POST /api/trading/resume/profile/:profileId

  • Purpose: Resume specific trading profile
  • Authentication: Required
  • Request Body: None

Orders & Positions

GET /api/orders

  • Purpose: Get user orders
  • Authentication: Required
  • Query Parameters: status, symbol, limit, offset
  • Response: Array of orders

GET /api/orders/:orderId

  • Purpose: Get specific order
  • Authentication: Required
  • Response: Order details

GET /api/positions

  • Purpose: Get open positions
  • Authentication: Required
  • Response: Array of positions

GET /api/positions/:positionId

  • Purpose: Get specific position
  • Authentication: Required
  • Response: Position details

POST /api/orders

  • Purpose: Create manual order
  • Authentication: Required
  • Request Body:
{
  "symbol": "string",
  "side": "buy" | "sell",
  "quantity": number,
  "orderType": "market" | "limit",
  "price": number | null
}

POST /api/orders/:orderId/cancel

  • Purpose: Cancel order
  • Authentication: Required
  • Request Body: None

Trade History

GET /api/trade-history

  • Purpose: Get closed trade history
  • Authentication: Required
  • Query Parameters: symbol, startDate, endDate, limit, offset
  • Response: Array of closed trades

GET /api/trade-history/:tradeId

  • Purpose: Get specific trade
  • Authentication: Required
  • Response: Trade details

Market Data

GET /api/market/quote/:symbol

  • Purpose: Get current quote for symbol
  • Authentication: Required
  • Response:
{
  "symbol": "string",
  "price": number,
  "change": number,
  "changePercent": number,
  "volume": number,
  "timestamp": number
}

GET /api/market/bars/:symbol

  • Purpose: Get OHLCV bars for symbol
  • Authentication: Required
  • Query Parameters: period, limit
  • Response: Array of OHLCV bars

Research & Screener

GET /api/research/profile/:symbol

  • Purpose: Get company profile
  • Authentication: Required
  • Response: Company profile data

GET /api/research/metrics/:symbol

  • Purpose: Get financial metrics
  • Authentication: Required
  • Response: Financial metrics

GET /api/screener

  • Purpose: Run stock screener
  • Authentication: Required
  • Query Parameters: Screener criteria
  • Response: Screener results

Backtesting

GET /api/backtest/strategies

  • Purpose: Get available backtest strategies
  • Authentication: Required
  • Feature Flag: ENABLE_BACKTEST
  • Response: Array of strategies

POST /api/backtest/run

  • Purpose: Run backtest
  • Authentication: Required
  • Feature Flag: ENABLE_BACKTEST
  • Request Body:
{
  "strategyId": "string",
  "symbol": "string",
  "startDate": "timestamp",
  "endDate": "timestamp",
  "initialCapital": number
}

GET /api/backtest/results/:backtestId

  • Purpose: Get backtest results
  • Authentication: Required
  • Feature Flag: ENABLE_BACKTEST
  • Response: Backtest results

Feature Flags

GET /api/feature-flags

  • Purpose: Get feature flags for authenticated user
  • Authentication: Required
  • Response:
{
  "backtest": {
    "enabled": boolean,
    "customerEnabled": boolean
  },
  "tabs": {
    "marketplace": boolean,
    "membership": boolean
  }
}

Admin Operations

GET /api/admin/audit

  • Purpose: Get audit events
  • Authentication: Required (admin role)
  • Query Parameters: userId, action, startDate, endDate, limit, offset
  • Response: Array of audit events

POST /api/admin/config

  • Purpose: Update dynamic config
  • Authentication: Required (admin role)
  • Request Body: Config update
  • Response: Updated config

GET /api/admin/config

  • Purpose: Get dynamic config
  • Authentication: Required (admin role)
  • Response: Current config

POST /internal/trading/pause

  • Purpose: Internal endpoint to pause trading
  • Authentication: Required (admin role, internal only)
  • Request Body:
{
  "reason": "string"
}

POST /internal/trading/resume

  • Purpose: Internal endpoint to resume trading
  • Authentication: Required (admin role, internal only)
  • Request Body: None

WebSocket Namespaces

/trading (User-Scoped)

Connection:

const socket = io(`${TRADING_API_URL}/trading`, {
  auth: { token: platformJwt }
});

Events:

Server → Client:

  • bot_state - Full bot state update
  • positions_update - Positions changed
  • orders_update - Orders changed
  • trade_closed - Trade closed
  • health_update - Backend health status

Client → Server:

  • subscribe_profiles - Subscribe to profile updates
  • unsubscribe_profiles - Unsubscribe from profile updates

Authentication: Required (platform JWT) Scoping: User receives only their own data


/admin (Admin-Only)

Connection:

const socket = io(`${TRADING_API_URL}/admin`, {
  auth: { token: platformJwt }
});

Events:

Server → Client:

  • all_bot_states - All users' bot states
  • system_health - System-wide health
  • audit_event - Audit event stream

Authentication: Required (admin role) Scoping: Admin receives cross-user state


/ (Root, Backward-Compatible)

Connection:

const socket = io(TRADING_API_URL, {
  auth: { token: platformJwt }
});

Events: Same as /trading namespace Authentication: Required Scoping: User receives only their own data


Error Responses

Standard Error Format

All errors follow this format:

{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": "Additional error details",
    "requestId": "x-request-id from request header"
  }
}

Common Error Codes

Code HTTP Status Description
UNAUTHORIZED 401 Missing or invalid authentication
FORBIDDEN 403 Insufficient permissions
NOT_FOUND 404 Resource not found
VALIDATION_ERROR 400 Request validation failed
RATE_LIMIT_EXCEEDED 429 Rate limit exceeded
INTERNAL_ERROR 500 Internal server error
SERVICE_UNAVAILABLE 503 Service temporarily unavailable

Rate Limiting

Current State

  • No explicit rate limiting implemented
  • Recommended: Add rate limiting to prevent API abuse
Endpoint Rate Limit Time Window
GET /api/* 100 requests 1 minute
POST /api/orders 10 requests 1 minute
POST /api/trading/* 20 requests 1 minute
WebSocket connections 5 connections 1 minute

Rate Limit Headers

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1715356800

Request ID Propagation

Header

x-request-id: uuid

Usage

  • All requests should include x-request-id header
  • If not provided, backend generates one
  • Backend echoes x-request-id in response header
  • Use x-request-id to trace requests across logs

Deprecation Policy

Deprecation Process

  1. Document endpoint in BACKEND_API_DEPRECATION.md
  2. Add X-Deprecated: true header to deprecated endpoint
  3. Add X-Deprecation-Date: YYYY-MM-DD header
  4. Add X-Sunset-Date: YYYY-MM-DD header (when endpoint will be removed)
  5. Provide migration guide in documentation
  6. Maintain deprecated endpoint for minimum 90 days

Example Deprecated Response

HTTP/1.1 200 OK
X-Deprecated: true
X-Deprecation-Date: 2026-05-09
X-Sunset-Date: 2026-08-09
Content-Type: application/json

{
  "data": {...},
  "deprecation": {
    "message": "This endpoint is deprecated. Use POST /api/v2/orders instead.",
    "migrationGuide": "/docs/api-migration.html#orders"
  }
}

OpenAPI/Swagger Generation

Use swagger-jsdoc to generate OpenAPI specification from JSDoc comments:

pnpm add -D swagger-jsdoc swagger-ui-express

Implementation Steps

  1. Add JSDoc comments to all API routes
  2. Generate OpenAPI specification
  3. Host Swagger UI
  4. Keep documentation in sync with code

Example JSDoc Comment

/**
 * @swagger
 * /api/orders:
 *   get:
 *     summary: Get user orders
 *     tags: [Orders]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *         description: Filter by order status
 *     responses:
 *       200:
 *         description: Orders retrieved successfully
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/Order'
 */
router.get('/api/orders', async (req, res) => {
  // implementation
});

Documentation Maintenance

When to Update Documentation

  • When adding new endpoints
  • When modifying existing endpoints
  • When deprecating endpoints
  • When changing authentication requirements
  • When adding new WebSocket events

Documentation Review Process

  1. Code review should check for documentation updates
  2. Ensure JSDoc comments are added for new endpoints
  3. Ensure OpenAPI spec is regenerated
  4. Update API reference document

Next Steps for API Documentation

Immediate (This Week)

  1. Create docs/API_REFERENCE.md with endpoint catalog
  2. Document authentication methods
  3. Document error responses
  4. Document WebSocket namespaces

Short-term (This Month)

  1. Add JSDoc comments to all API routes
  2. Generate OpenAPI specification
  3. Host Swagger UI
  4. Add request/response examples

Medium-term (This Quarter)

  1. Implement rate limiting
  2. Add rate limiting documentation
  3. Add API versioning
  4. Create API migration guide

References

  • BACKEND_API_DEPRECATION.md - Deprecated endpoints
  • BACKEND_AUDIT_SCHEMA.md - Audit event schema
  • backend/src/services/apiServer.ts - API implementation
  • shared/realtime.ts - WebSocket namespace definitions