# Admin Trading Monitor

> **Super Admin Only** — Real-time monitoring of all trading activity across all users.

## Overview

The Admin Trading Monitor (`/admin/trading-monitor`) provides super admins with a unified view of all platform trading activity for troubleshooting, compliance monitoring, and performance validation.

## Access

- **URL**: `/admin/trading-monitor`
- **Required Role**: `super_admin`
- **API Base**: `/api/predict/v1/admin/trading/monitor`

## Features

### 1. Real-Time Dashboard

Auto-refreshing dashboard with configurable intervals (2s, 5s, 10s, 30s):

| Stat Card | Description |
|-----------|-------------|
| **Active Runs** | Paper + Live algorithm runs currently executing |
| **Combined Equity** | Total equity across all active runs |
| **Trades Today** | Algorithm trades executed today |
| **Mock Trades** | Mock credit trades today + total portfolio equity |
| **Guardrail Kills** | Algorithm stops by safety guardrails |
| **AI Credits** | LLM usage cost and call count |
| **Broker Latency** | Average fill latency across brokers |
| **Decision Latency** | AI decision time (tick start to trade decision) |

### 2. Filter Controls

| Filter | Description |
|--------|-------------|
| **User Filter** | Search by email (partial match) |
| **Time Range** | 1h, 6h, 24h, 48h, or 7 days |
| **Include Backtests** | Toggle to show backtest data |

### 3. Tabs

#### Active Runs Tab
Shows all running paper and live algorithms:
- Algorithm name and user
- Mode (PAPER/LIVE with visual indicator)
- Equity, PnL, drawdown, positions, trades, win rate
- Last tick time and action
- Expandable details: indicators, positions JSON
- **Stop button** to force-stop any algorithm

#### Algo Trades Tab
Trades from `predict.algorithm_trades` (DSL-based algorithms):
- Time, user, algorithm, mode, symbol
- Side (BUY/SELL), quantity, price
- Slippage (bps), realized PnL

#### Mock/Manual Trades Tab
Trades from `trading.mock_trades` (credits system):
- Time, user, portfolio name
- Mode (MOCK/PAPER/LIVE)
- Source (USER/AI/ALGO/AUTO)
- Symbol, side, quantity, price, total value, PnL

**Source Classification:**
| Source | Description |
|--------|-------------|
| USER | Manual trades placed by users |
| AI | AI signal-assisted (confidence < 85%) |
| ALGO | Algorithm-driven trades |
| AUTO | Fully autonomous (confidence ≥ 85%) |

#### Guardrail Kills Tab
Algorithm stops by safety guardrails:
- Triggered by (system, admin, user)
- Layer (L1 max drawdown, L2 consecutive loss, etc.)
- Reason and metric value

#### AI Usage Tab
LLM calls with billing details:
- Billing mode (subscription/credits/byok)
- Model, endpoint, input/output tokens
- Cost in credits

#### Broker Latency Tab
Execution performance by broker and mode:

| Metric | Description | Color Coding |
|--------|-------------|--------------|
| Avg Accept | Time to broker acknowledgment | Green <500ms |
| Avg Fill | Time from submit to fill | Green <1s |
| P95 Fill | 95th percentile fill latency | Green <1s, Yellow <2s |
| Fill Rate | % of orders filled | Green ≥95% |

#### Decision Latency Tab
AI decision-making performance from tick start to trade decision:

**Summary Stats:**
| Stat | Description |
|------|-------------|
| Avg Decision Time | Average time for AI to make trading decision |
| P95 Decision Time | 95th percentile decision latency |
| Slowest Decision | Maximum decision time in the period |
| Total Ticks Today | Number of decision ticks processed |

**Latency Breakdown by Phase:**
| Phase | Description | Typical Range |
|-------|-------------|---------------|
| Price Fetch | Time to retrieve market prices | 50-200ms |
| Context Prefetch | Macro, bonds, sentiment data | 100-500ms |
| PINN Prediction | Physics-informed neural network (if used) | 200-2000ms |
| Rule Evaluation | Entry/exit condition evaluation | 10-100ms |
| Broker Submit | Time to submit order (live mode) | 50-500ms |
| Broker Fill | Time to receive fill confirmation | 100-2000ms |

**Color Coding:**
- **Green**: <2000ms total — healthy performance
- **Yellow**: 2000-5000ms — investigate bottlenecks
- **Red**: >5000ms — potential issues

**Slowest Phase Detection:**
Each tick shows the phase that contributed most to latency, helping identify:
- Slow data provider responses
- PINN model inference overhead
- Broker connectivity issues
- Complex rule evaluation

#### Backtests Tab (Optional)
Historical backtest results when "Include Backtests" is enabled.

## Data Sources

### Algorithm Trading System
```
predict.algorithm_runs             → Active/completed algorithm runs
predict.algorithm_trades           → Trades from DSL-based algorithms
predict.algorithm_kills            → Guardrail stop events
predict.algorithm_run_status       → Real-time tick status
predict.algorithm_live_metrics     → Equity curve telemetry
predict.algorithm_decision_latency → Decision timing per tick (NEW)
```

### Mock/Manual Trading System
```
trading.mock_portfolios → User portfolios with credits
trading.mock_trades     → All mock/paper/live trades
trading.positions       → Open positions
```

### Broker Execution
```
predict.broker_orders → Order timestamps for latency
predict.broker_fills  → Individual fill events
```

### AI Billing
```
billing.ai_credit_transactions → LLM usage records
billing.user_ai_billing        → User billing mode
```

## API Endpoints

### GET /api/predict/v1/admin/trading/monitor
Returns all monitor data.

**Query Parameters:**
| Param | Type | Default | Description |
|-------|------|---------|-------------|
| userFilter | string | '' | Filter by email (partial match) |
| hoursBack | number | 24 | Hours of history (1-168) |
| includeBacktests | boolean | false | Include backtest data |

**Response:**
```typescript
{
  activeRuns: ActiveRun[];
  recentTrades: RecentTrade[];
  recentMockTrades: MockTrade[];
  recentKills: RecentKill[];
  recentCreditUsage: CreditUsage[];
  recentBacktests: BacktestResult[];
  brokerLatency: BrokerLatencyStats[];
  stats: {
    totalActiveRuns: number;
    paperRuns: number;
    liveRuns: number;
    totalTradesToday: number;
    totalMockTradesToday: number;
    totalKillsToday: number;
    combinedEquity: number;
    combinedPnl: number;
    totalCreditUsageTodayCents: number;
    totalAiCallsToday: number;
    totalBrokerOrders: number;
    avgBrokerLatencyMs: number | null;
  };
  filters: { userFilter, hoursBack, includeBacktests };
}
```

### GET /api/predict/v1/admin/trading/monitor/:runId
Returns detailed info for a specific run including trades, kills, and equity telemetry.

### POST /api/predict/v1/admin/trading/monitor/:runId
Force stops a running algorithm.

## Trading Progression Flow

The monitor tracks the full progression from development to production:

```
1. MOCK MODE (Credits System)
   └─ trading.mock_trades with executionMode='mock'
   └─ Simulated $100k balance
   └─ Internal testing, no broker

2. PAPER MODE (Live Data, No Real Money)
   └─ trading.mock_trades with executionMode='paper'
   └─ Connected broker, real market prices
   └─ Latency tracking via predict.broker_orders

3. LIVE MODE (Real Money)
   └─ trading.mock_trades with executionMode='live'
   └─ Real broker execution
   └─ Full latency and fill rate monitoring
```

## Broker Latency Tracking

Latency is calculated from `predict.broker_orders`:

```sql
-- Accept latency: time to broker acknowledgment
accepted_at - submitted_at

-- Fill latency: total execution time
filled_at - submitted_at
```

**Performance Thresholds:**
| Metric | Good | Warning | Poor |
|--------|------|---------|------|
| Accept Latency | <500ms | 500-1000ms | >1000ms |
| Fill Latency | <1000ms | 1000-2000ms | >2000ms |
| P95 Fill | <1000ms | 1000-2000ms | >2000ms |
| Fill Rate | ≥95% | 80-95% | <80% |

## Admin Actions

### Force Stop Algorithm
1. Click "Stop" button on any active run
2. Confirms with dialog
3. Calls `stopRun()` to flatten positions
4. Records kill event with `triggered_by='admin'`

## Files

| File | Description |
|------|-------------|
| `packages/be/src/admin/trading/handlers.ts` | Backend handlers |
| `apps/web/src/app/admin/trading-monitor/page.tsx` | Frontend page |
| `apps/web/src/app/api/predict/v1/admin/trading/monitor/route.ts` | API route |
| `apps/web/src/app/api/predict/v1/admin/trading/monitor/[runId]/route.ts` | Run detail route |

## Related Documentation

- [Algorithm Builder](12-algorithm-builder.md) — DSL and algorithm execution
- [Broker Integration](13-broker-integration.md) — Broker adapters and execution modes
- [AI Billing Credits](42-ai-billing-credits-plan.md) — Credits system and BYOK
- [Trading Workflow](33-trading-workflow.md) — 6-stage trading workflow
