-- ============================================================================
-- Schema: trading
-- Table: trading_metrics
-- Description: Métricas diarias de performance por bot
-- Dependencies: trading.bots
-- ============================================================================

CREATE TABLE trading.trading_metrics (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Referencias
  bot_id UUID NOT NULL REFERENCES trading.bots(id) ON DELETE CASCADE,

  -- Período
  metric_date DATE NOT NULL,

  -- Capital
  starting_capital DECIMAL(20,8) NOT NULL,
  ending_capital DECIMAL(20,8) NOT NULL,
  peak_capital DECIMAL(20,8) NOT NULL,

  -- Trading
  total_trades INTEGER DEFAULT 0,
  winning_trades INTEGER DEFAULT 0,
  losing_trades INTEGER DEFAULT 0,

  -- PnL
  gross_profit DECIMAL(20,8) DEFAULT 0,
  gross_loss DECIMAL(20,8) DEFAULT 0,
  net_profit DECIMAL(20,8) DEFAULT 0,

  -- Ratios
  win_rate DECIMAL(5,2) DEFAULT 0,
  profit_factor DECIMAL(10,4) DEFAULT 0, -- gross_profit / gross_loss
  sharpe_ratio DECIMAL(10,4),
  max_drawdown DECIMAL(10,4) DEFAULT 0,

  -- Trades
  avg_win DECIMAL(20,8) DEFAULT 0,
  avg_loss DECIMAL(20,8) DEFAULT 0,
  largest_win DECIMAL(20,8) DEFAULT 0,
  largest_loss DECIMAL(20,8) DEFAULT 0,

  -- Tiempos promedio
  avg_trade_duration_minutes INTEGER,

  -- Metadata
  metadata JSONB DEFAULT '{}',

  -- Timestamps
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  -- Constraint: una métrica por bot por día
  CONSTRAINT uq_trading_metrics_bot_date UNIQUE (bot_id, metric_date)
);

-- Índices
CREATE INDEX idx_trading_metrics_bot ON trading.trading_metrics(bot_id);
CREATE INDEX idx_trading_metrics_date ON trading.trading_metrics(metric_date DESC);
CREATE INDEX idx_trading_metrics_bot_date ON trading.trading_metrics(bot_id, metric_date DESC);

-- Comentarios
COMMENT ON TABLE trading.trading_metrics IS 'Métricas diarias de performance por bot';
COMMENT ON COLUMN trading.trading_metrics.profit_factor IS 'Ratio gross_profit / gross_loss (>1 es rentable)';
COMMENT ON COLUMN trading.trading_metrics.sharpe_ratio IS 'Ratio de Sharpe ajustado por riesgo';
COMMENT ON COLUMN trading.trading_metrics.max_drawdown IS 'Máximo drawdown del día (%)';
