-- Migración incremental: añadir columnas faltantes para WebTrader

-- trading_orders: dirección (buy/sell)
ALTER TABLE trading_orders
    ADD COLUMN IF NOT EXISTS direction ENUM('buy','sell') NOT NULL DEFAULT 'buy';

-- trading_orders: precio y tiempo de llenado (fill)
ALTER TABLE trading_orders
    ADD COLUMN IF NOT EXISTS fill_price DECIMAL(12,6) NULL,
    ADD COLUMN IF NOT EXISTS fill_time DATETIME NULL;

-- trading_positions: referencia a orden y precio de cierre
ALTER TABLE trading_positions
    ADD COLUMN IF NOT EXISTS order_id INT NULL,
    ADD COLUMN IF NOT EXISTS close_price DECIMAL(12,6) NULL,
    ADD COLUMN IF NOT EXISTS close_time DATETIME NULL,
    ADD COLUMN IF NOT EXISTS commission DECIMAL(12,6) DEFAULT 0.0000,
    ADD COLUMN IF NOT EXISTS swap DECIMAL(12,6) DEFAULT 0.0000,
    ADD COLUMN IF NOT EXISTS comment TEXT NULL;

-- trading_accounts: nivel de margen
ALTER TABLE trading_accounts
    ADD COLUMN IF NOT EXISTS margin_level DECIMAL(8,2) DEFAULT 0.00;

-- Opcional: asegurar índices si faltan
CREATE INDEX IF NOT EXISTS idx_trading_orders_account_time ON trading_orders(account_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_trading_positions_account_time ON trading_positions(account_id, opened_at DESC);
CREATE INDEX IF NOT EXISTS idx_trading_history_account_time ON trading_history(account_id, closed_at DESC);
