Skip to main content
POST
/
api
/
rpc
/
variants.getVariantStats
Get Variant Stats
curl --request POST \
  --url https://api.example.com/api/rpc/variants.getVariantStats
{
  "stats": [
    {
      "variantId": {},
      "label": "<string>",
      "color": "<string>",
      "totalTrades": 123,
      "winRate": 123,
      "totalPnl": 123,
      "avgPnl": 123,
      "modelCount": 123
    }
  ]
}

Overview

Returns comprehensive performance statistics for all trading variants, aggregated across all models using each variant. This endpoint calculates win rates, P&L metrics, and model counts by analyzing closed orders and active models.

Request

Input Schema

{
  // No input parameters required
}
This endpoint automatically aggregates statistics for all variants.

Response

Output Schema

stats
array
required
Array of variant statistics objects

Example Response

{
  "stats": [
    {
      "variantId": "Apex",
      "label": "Apex (Kelly Engine)",
      "color": "#a855f7",
      "totalTrades": 847,
      "winRate": 62.34,
      "totalPnl": 3248.56,
      "avgPnl": 3.84,
      "modelCount": 12
    },
    {
      "variantId": "Trendsurfer",
      "label": "Trendsurfer (Momentum)",
      "color": "#06b6d4",
      "totalTrades": 623,
      "winRate": 58.91,
      "totalPnl": 1876.23,
      "avgPnl": 3.01,
      "modelCount": 8
    },
    {
      "variantId": "Contrarian",
      "label": "Contrarian (Reverter)",
      "color": "#e11d48",
      "totalTrades": 412,
      "winRate": 54.13,
      "totalPnl": -234.67,
      "avgPnl": -0.57,
      "modelCount": 5
    },
    {
      "variantId": "Sovereign",
      "label": "Sovereign (Adaptive)",
      "color": "#eab308",
      "totalTrades": 0,
      "winRate": 0,
      "totalPnl": 0,
      "avgPnl": 0,
      "modelCount": 0
    }
  ]
}

Statistics Calculations

Aggregation Logic

For each variant, the endpoint:
  1. Finds all models using the variant (SELECT * FROM "Models" WHERE variant = ?)
  2. Retrieves closed orders for those models (WHERE status = 'CLOSED' AND modelId IN (...))
  3. Calculates metrics from the order data:
    • totalTrades: Count of closed orders
    • winRate: (wins / totalTrades) * 100 where wins = orders with realizedPnl > 0
    • totalPnl: Sum of all realizedPnl values
    • avgPnl: totalPnl / totalTrades
    • modelCount: Count of active models

Zero-Value Handling

If no models exist for a variant:
  • All numeric fields return 0
  • The variant is still included in the response for completeness

Performance Considerations

  • Uses database indexes on models.variant and orders.status
  • Runs parallel queries for all variants using Promise.all()
  • SQL array operations (ANY(modelIds)) for efficient filtering

Usage

import { useQuery } from "@tanstack/react-query";
import { orpc } from "@/server/orpc/client";

function VariantStatsTable() {
  const { data, isLoading, error } = useQuery(
    orpc.variants.getVariantStats.queryOptions({ input: {} })
  );

  if (isLoading) return <div>Loading stats...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <table className="min-w-full">
      <thead>
        <tr>
          <th>Variant</th>
          <th>Models</th>
          <th>Total Trades</th>
          <th>Win Rate</th>
          <th>Total P&L</th>
          <th>Avg P&L</th>
        </tr>
      </thead>
      <tbody>
        {data.stats.map((stat) => (
          <tr key={stat.variantId}>
            <td>
              <span style={{ color: stat.color }}>{stat.label}</span>
            </td>
            <td>{stat.modelCount}</td>
            <td>{stat.totalTrades}</td>
            <td>{stat.winRate.toFixed(2)}%</td>
            <td className={stat.totalPnl >= 0 ? "text-green-600" : "text-red-600"}>
              ${stat.totalPnl.toFixed(2)}
            </td>
            <td>${stat.avgPnl.toFixed(2)}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

Performance Metrics

Database Queries

  • Per variant: 2 queries (models lookup + orders aggregation)
  • Total queries: 2 × number of variants (currently 8 queries)
  • Execution: Parallel via Promise.all()
  • Average latency: 50-150ms depending on order volume

Indexes Used

-- Optimizes model filtering by variant
CREATE INDEX idx_models_variant ON "Models"(variant);

-- Optimizes closed order lookups
CREATE INDEX idx_orders_status_model ON "Orders"(status, "modelId");

Monitoring

The endpoint is wrapped in a Sentry performance span:
Sentry.startSpan({ name: "variants.getVariantStats" }, async () => {
  // Statistics calculation
});

Understanding the Metrics

Definition: Percentage of trades that closed with positive P&LCalculation: (winning_trades / total_trades) × 100Interpretation:
  • > 55%: Strong performance
  • 50-55%: Moderate performance
  • < 50%: Underperforming
Note: Win rate alone doesn’t indicate profitability. A 40% win rate with high R:R can be more profitable than 60% with low R:R.
Definition: Mean profit/loss per closed tradeCalculation: total_pnl / total_tradesInterpretation:
  • > 0: Profitable on average
  • < 0: Losing on average
  • Magnitude indicates risk-adjusted returns
Use case: Compare avgPnl across variants to identify most efficient strategies
Definition: Number of active models currently using the variantNote: This is a snapshot count, not historical. Models can be:
  • Actively trading (status = ACTIVE)
  • Paused (status = PAUSED)
  • Any status except DELETED
Use case: Gauge variant adoption and allocation

Get Variants

List all available variants and their configurations

Get Variant History

View historical portfolio performance per variant

Best Practices

Statistics are calculated on-demand and can be expensive for large datasets. Consider:
  • Implementing server-side caching with TTL
  • Using SSE subscriptions for real-time updates
  • Pre-aggregating stats in a materialized view
For dashboards displaying multiple metrics, fetch all variant data in a single batch:
const [variants, stats, history] = await Promise.all([
  queryClient.ensureQueryData(orpc.variants.getVariants.queryOptions({ input: {} })),
  queryClient.ensureQueryData(orpc.variants.getVariantStats.queryOptions({ input: {} })),
  queryClient.ensureQueryData(orpc.variants.getVariantHistory.queryOptions({ input: { window: "7d" } })),
]);

Build docs developers (and LLMs) love