# POST /v1/validate

The core endpoint. Analyzes a proposed trade against real-time market data and returns a structured risk assessment.

## Request

```
POST https://api.canonprotocol.org/v1/validate
```

### Headers

| Header | Required | Value |
|---|---|---|
| `Authorization` | Yes | `Bearer YOUR_API_KEY` |
| `Content-Type` | Yes | `application/json` |

### Body

```json
{
  "asset": "BTC",
  "action": "long",
  "size": 50000,
  "leverage": 10,
  "wallet": "0x7a3b1234567890abcdef1234567890abcdef1234",
  "mode": "cross"
}
```

| Field | Type | Required | Description |
|---|---|---|---|
| `asset` | string | Yes | Asset ticker (e.g. `"BTC"`, `"ETH"`, `"HYPE"`) |
| `action` | string | Yes | Trade direction: `"long"`, `"short"`, or `"close"` |
| `size` | number | Yes | Position size in USD. Must be positive, max $100,000,000 |
| `leverage` | number | No | Leverage multiplier. Cannot exceed the asset's maximum leverage |
| `wallet` | string | Yes | Ethereum wallet address (42 characters, `0x` prefix) |
| `mode` | string | No | Margin mode: `"cross"` (default) or `"isolated"` |
| `monte_carlo` | boolean | No | Enable Monte Carlo simulation in the response (default: `false`) |

### Validation Rules

- `wallet` must be a valid 42-character hex address starting with `0x`
- `size` must be positive and not exceed $100M
- `leverage` cannot exceed the asset's maximum allowed leverage
- `asset` must be a currently listed (not delisted) asset on Hyperliquid
- Some assets are isolated-margin only and will reject `"cross"` mode

## Response

```json
{
  "risk_score": 42,
  "recommendation": "proceed_with_caution",
  "flags": ["funding_anomaly"],
  "slippage": {
    "bps": 5.2,
    "fill_price": 67432.10,
    "mid_price": 67420.00,
    "depth_50bps": 2150000,
    "depth_100bps": 4800000,
    "bid_ask_imbalance": 0.12
  },
  "liquidation": {
    "price": 61200.50,
    "distance_pct": 9.2,
    "margin_used_pct": 68.4,
    "effective_leverage": 10.8,
    "mode": "cross"
  },
  "funding": {
    "funding_rate": 0.000012,
    "annualized_pct": 9.7,
    "vs_cex_divergence": 1.8,
    "direction": "longs_pay",
    "agent_pays": true
  },
  "impact": {
    "expected_bps": 8.1,
    "participation_pct": 2.3
  },
  "var": {
    "pct_95_24h": 4.2,
    "pct_99_24h": 6.8,
    "dollar_95_24h": 2100,
    "dollar_99_24h": 3400,
    "lvar_95_24h": 2250,
    "lvar_99_24h": 3650,
    "es_95_24h": 5.1,
    "es_99_24h": 8.3,
    "margin_var_99_pct": 68.0
  },
  "oi": {
    "current": 485000000,
    "at_cap": false,
    "utilization_pct": 72.3
  },
  "stress": [
    {
      "scenario": "luna_collapse",
      "description": "LUNA/UST collapse (May 2022): -30% BTC, severe alt drawdowns",
      "pnl_pct": -37.0,
      "pnl_usd": -18500,
      "funding_cost_pct": 2.1,
      "liquidity_cost_pct": 1.8,
      "liquidation_distance_pct": 3.2,
      "survives": true
    }
  ],
  "portfolio_risk": {
    "portfolio_var_99_24h": 8200,
    "portfolio_es_99_24h": 12500,
    "position_count": 3
  },
  "portfolio_stress": {
    "scenario": "ftx_crash",
    "total_pnl_usd": -24000,
    "total_pnl_pct": -12.5,
    "total_funding_cost_pct": 3.2,
    "account_survives": true,
    "positions_liquidated": 0
  },
  "fees": {
    "taker_fee_bps": 3.5,
    "estimated_fee_usd": 17.50,
    "fee_pct_of_margin": 0.35
  },
  "cost_analysis": {
    "total_entry_cost_bps": 16.8,
    "total_round_trip_cost_bps": 33.6,
    "breakeven_move_pct": 0.34,
    "funding_drag_24h_pct": 0.027,
    "cost_score": 0.17
  },
  "sizing": {
    "max_safe_size_usd": 1250000,
    "suggested_size_usd": 875000,
    "size_limit_reason": "book_depth"
  },
  "meta": {
    "asset": "BTC",
    "mark_price": 67500.00,
    "max_leverage": 50,
    "latency_ms": 52,
    "request_id": "req_d4f8a2b1"
  },
  "model_version": {
    "engine_version": "0.2.0"
  }
}
```

### Top-Level Fields

| Field | Type | Description |
|---|---|---|
| `risk_score` | number | Composite risk score from 0 (lowest risk) to 100 (highest risk) |
| `recommendation` | string | `"proceed"`, `"proceed_with_caution"`, or `"abort"` |
| `flags` | string[] | Array of risk flags identifying specific concerns. See [Risk Flags](/llm/risk/flags.md) |
| `slippage` | object | Order book slippage analysis |
| `liquidation` | object | Liquidation proximity metrics |
| `funding` | object | Funding rate analysis |
| `impact` | object | Market impact estimation |
| `var` | object | Value-at-Risk calculations |
| `oi` | object | Open interest utilization |
| `stress` | array | Stress test results against historical scenarios |
| `portfolio_risk` | object or null | Portfolio-level risk (present when wallet has existing positions) |
| `portfolio_stress` | object or null | Portfolio-level stress test (present when wallet has existing positions) |
| `fees` | object | Estimated trading fees |
| `cost_analysis` | object | Trade cost aggregation and breakeven analysis |
| `sizing` | object or null | Position sizing guidance based on market conditions. Omitted in error responses |
| `monte_carlo` | object or null | Monte Carlo simulation results. Present when `"monte_carlo": true` in request |
| `evt` | object or null | Extreme Value Theory tail risk estimates |
| `greeks` | object or null | Position Greeks (delta, gamma, vega, theta, liquidation gamma) |
| `regime` | object or null | Liquidity regime state (normal/stressed/crisis) |
| `drawdown` | object or null | Drawdown metrics and stop-loss suggestions |
| `portfolio_attribution` | object or null | Marginal/component VaR decomposition |
| `meta` | object | Request metadata including current mark price and latency |
| `model_version` | object | Engine version and calibration identifiers |

### Slippage Object

| Field | Type | Description |
|---|---|---|
| `bps` | number | Expected slippage in basis points |
| `fill_price` | number | Estimated average fill price |
| `mid_price` | number | Current mid price from the order book |
| `depth_50bps` | number | USD liquidity available within 50bps of mid |
| `depth_100bps` | number | USD liquidity available within 100bps of mid |
| `bid_ask_imbalance` | number | Order book imbalance ratio (-1 to 1). Positive = bid-heavy (buying pressure), 0 = balanced |

### Liquidation Object

| Field | Type | Description |
|---|---|---|
| `price` | number | Estimated liquidation price |
| `distance_pct` | number | Distance from mark price to liquidation as percentage |
| `margin_used_pct` | number | Percentage of available margin consumed |
| `effective_leverage` | number | Effective leverage accounting for existing positions |
| `mode` | string | Margin mode used for calculation: `"cross"`, `"isolated"`, or `"close"` |

### Funding Object

| Field | Type | Description |
|---|---|---|
| `funding_rate` | number | Current hourly funding rate (1/8th of the 8-hour rate) |
| `annualized_pct` | number | Projected annualized funding cost as percentage |
| `vs_cex_divergence` | number | Ratio of Hyperliquid to CEX funding rate (e.g. 3.0 = HL rate is 3x CEX). 0 when rates are negligible |
| `direction` | string | `"longs_pay"` or `"shorts_pay"` |
| `agent_pays` | boolean | `true` if the agent pays funding (a cost), `false` if the agent receives funding (income). When `false`, the funding component contributes zero to the risk score |

### Impact Object

| Field | Type | Description |
|---|---|---|
| `expected_bps` | number | Estimated market impact in basis points |
| `participation_pct` | number | Trade size as percentage of recent volume |

### VaR Object

| Field | Type | Description |
|---|---|---|
| `pct_95_24h` | number | 24-hour Value-at-Risk at 95% confidence (percentage of notional) |
| `pct_99_24h` | number | 24-hour Value-at-Risk at 99% confidence (percentage of notional) |
| `dollar_95_24h` | number | 95% VaR in USD |
| `dollar_99_24h` | number | 99% VaR in USD |
| `lvar_95_24h` | number | Liquidity-adjusted VaR at 95% in USD (includes spread and slippage costs) |
| `lvar_99_24h` | number | Liquidity-adjusted VaR at 99% in USD |
| `pct_99_4h` | number | 4-hour Value-at-Risk at 99% confidence (percentage of notional) |
| `pct_99_7d` | number | 7-day Value-at-Risk at 99% confidence (percentage of notional) |
| `dollar_99_4h` | number | 4-hour 99% VaR in USD |
| `dollar_99_7d` | number | 7-day 99% VaR in USD |
| `es_95_24h` | number | Expected Shortfall (CVaR) at 95% confidence |
| `es_99_24h` | number | Expected Shortfall (CVaR) at 99% confidence |
| `margin_var_99_pct` | number | VaR as percentage of margin (not notional). At 20x leverage, 5% notional VaR = 100% margin VaR |
| `volatility_regime` | string | Current volatility regime: `"low"`, `"normal"`, or `"high"` |
| `volatility_forecast` | object or null | GARCH volatility forecast. See Volatility Forecast Object below |

### OI Object

| Field | Type | Description |
|---|---|---|
| `current` | number | Current open interest in USD |
| `at_cap` | boolean | Whether the asset is at Hyperliquid's OI cap |
| `utilization_pct` | number | OI as percentage of estimated cap |

### Stress Array

Each entry in the `stress` array represents a historical scenario:

| Field | Type | Description |
|---|---|---|
| `scenario` | string | Scenario identifier |
| `description` | string | Human-readable description of the scenario |
| `pnl_pct` | number | Estimated PnL as percentage of position |
| `pnl_usd` | number | Estimated PnL in USD |
| `funding_cost_pct` | number | Projected funding cost under the scenario |
| `liquidity_cost_pct` | number | Estimated liquidity/slippage cost under the scenario |
| `liquidation_distance_pct` | number | Distance to liquidation under the scenario |
| `survives` | boolean | Whether the position would survive the scenario |

### Portfolio Risk Object

Present only when the wallet has 2 or more open positions. Omitted from response otherwise.

| Field | Type | Description |
|---|---|---|
| `portfolio_var_99_24h` | number | Portfolio-level 99% VaR in USD, accounting for correlations |
| `portfolio_es_99_24h` | number | Portfolio-level Expected Shortfall at 99% in USD |
| `position_count` | integer | Number of open positions in the portfolio |
| `monte_carlo` | object or null | Portfolio-level Monte Carlo simulation results (VaR, ES, marginal/component VaR, liquidation probability) |
| `tail_dependence` | array or null | Copula-based tail dependence between position pairs (lower/upper tail lambda, Pearson rho) |

### Portfolio Stress Object

Present only when the wallet has existing positions. Omitted from response otherwise.

| Field | Type | Description |
|---|---|---|
| `scenario` | string | Worst-case scenario for the portfolio |
| `total_pnl_usd` | number | Total portfolio PnL under the scenario |
| `total_pnl_pct` | number | Total portfolio PnL as percentage |
| `total_funding_cost_pct` | number | Combined funding cost across all positions |
| `account_survives` | boolean | Whether the account would survive |
| `positions_liquidated` | integer | Number of positions that would be liquidated |

### Fees Object

| Field | Type | Description |
|---|---|---|
| `taker_fee_bps` | number | Taker fee rate in basis points |
| `estimated_fee_usd` | number | Estimated fee for this trade in USD |
| `fee_pct_of_margin` | number | Fee as percentage of margin posted |

### Cost Analysis Object

| Field | Type | Description |
|---|---|---|
| `total_entry_cost_bps` | number | Total entry cost in basis points (slippage + impact + taker fee) |
| `total_round_trip_cost_bps` | number | Estimated round-trip cost (entry + exit) in basis points |
| `breakeven_move_pct` | number | Price movement percentage needed to break even after all costs, accounting for leverage |
| `funding_drag_24h_pct` | number | Projected 24-hour funding cost as percentage of margin. Negative means the agent receives funding |
| `cost_score` | number | Normalized cost burden from 0.0 (negligible) to 1.0 (extremely expensive) |

### Sizing Object

Present when the engine can compute sizing guidance. Omitted in error responses.

| Field | Type | Description |
|---|---|---|
| `max_safe_size_usd` | number | Largest position size (USD) that keeps all risk metrics within safe thresholds |
| `suggested_size_usd` | number | Recommended position size with safety margin applied |
| `size_limit_reason` | string | The binding constraint: `"book_depth"`, `"oi_capacity"`, `"margin_headroom"`, or `"market_impact"` |

### Monte Carlo Object

Present when `"monte_carlo": true` is passed in the request body.

| Field | Type | Description |
|---|---|---|
| `simulations` | number | Number of Monte Carlo paths simulated |
| `var_95` | number | 95% VaR from simulation (percentage) |
| `var_99` | number | 99% VaR from simulation (percentage) |
| `expected_shortfall_95` | number | Expected Shortfall at 95% from simulation |
| `expected_shortfall_99` | number | Expected Shortfall at 99% from simulation |
| `median_return` | number | Median simulated return |
| `worst_case` | number | Worst-case simulated return |
| `confidence_interval` | array | [lower, upper] bounds of the 95% confidence interval |

### EVT Object

Tail risk estimates beyond standard VaR.

| Field | Type | Description |
|---|---|---|
| `var_99_9` | number | 99.9% VaR estimate (percentage) |
| `expected_shortfall_99_9` | number | 99.9% Expected Shortfall |

### Greeks Object

Position-level Greeks for sensitivity analysis.

| Field | Type | Description |
|---|---|---|
| `delta` | number | Price sensitivity (dPnL / dPrice) |
| `gamma` | number | Second-order price sensitivity (dDelta / dPrice) |
| `vega` | number | Volatility sensitivity (dPnL / dVol) |
| `theta` | number | Time decay (daily PnL erosion from funding and costs) |
| `liquidation_gamma` | number | Gamma-like measure of liquidation distance sensitivity to price moves |

### Regime Object

Current liquidity regime classification.

| Field | Type | Description |
|---|---|---|
| `state` | string | `"normal"`, `"stressed"`, or `"crisis"` |
| `confidence` | number | Confidence in the regime classification (0.0 to 1.0) |

### Drawdown Object

Drawdown metrics and suggested stop-loss levels.

| Field | Type | Description |
|---|---|---|
| `max_drawdown_pct` | number | Maximum historical drawdown percentage for the asset |
| `current_drawdown_pct` | number | Current drawdown from recent peak |
| `peak_equity` | number | Peak equity value before drawdown |
| `trough_equity` | number | Trough equity value during drawdown |
| `drawdown_duration_hours` | number | Duration of the current drawdown in hours |
| `calmar_ratio` | number | Return-to-max-drawdown ratio |
| `trailing_stop_distance_pct` | number | ATR-based trailing stop distance as percentage |
| `suggested_stop_loss_pct` | number | Suggested stop-loss percentage based on volatility and leverage |

### Portfolio Attribution Object

Marginal and component VaR decomposition across portfolio positions.

| Field | Type | Description |
|---|---|---|
| `total_var_99` | number | Total portfolio 99% VaR in USD |
| `diversification_benefit_pct` | number | Percentage reduction in VaR from diversification |
| `positions` | array | Per-position attribution breakdown |

Each entry in the `positions` array:

| Field | Type | Description |
|---|---|---|
| `asset` | string | Asset ticker |
| `marginal_var` | number | Marginal VaR contribution in USD (change in portfolio VaR from adding this position) |
| `component_var` | number | Component VaR in USD (position's share of total portfolio VaR) |
| `component_var_pct` | number | Component VaR as percentage of total portfolio VaR |

### Meta Object

| Field | Type | Description |
|---|---|---|
| `asset` | string | Asset ticker |
| `mark_price` | number | Current mark price |
| `max_leverage` | number | Maximum allowed leverage for this asset |
| `latency_ms` | number | Server-side processing time in milliseconds |
| `request_id` | string or null | Unique identifier for this request |
| `error` | string or null | Error message (present only in batch error responses) |

### Model Version Object

| Field | Type | Description |
|---|---|---|
| `engine_version` | string | Semantic version of the risk engine |

### Volatility Forecast Object

Volatility forecast at multiple horizons.

| Field | Type | Description |
|---|---|---|
| `sigma_1h` | number | Forecasted 1-hour volatility (annualized) |
| `sigma_4h` | number | Forecasted 4-hour volatility (annualized) |
| `sigma_1d` | number | Forecasted 1-day volatility (annualized) |
| `sigma_7d` | number | Forecasted 7-day volatility (annualized) |
| `long_run_sigma` | number | Long-run unconditional volatility |
