-- ============================================================
-- 异常订单检查 SQL
-- 可以直接在 SQLite 命令行或数据库管理工具中执行
-- ============================================================

-- 1. 检查 OPEN 状态但成交价无效的订单（最可能的问题来源）
SELECT
    order_id,
    symbol,
    side,
    status,
    entry_price,
    filled_price,
    created_at,
    'OPEN状态但成交价无效' as issue
FROM paper_orders
WHERE status = 'OPEN'
  AND (filled_price IS NULL OR filled_price = 0);

-- 2. 检查 PENDING 状态但有成交价的订单（状态不一致）
SELECT
    order_id,
    symbol,
    side,
    status,
    entry_price,
    filled_price,
    created_at,
    'PENDING状态但有成交价' as issue
FROM paper_orders
WHERE status = 'PENDING'
  AND filled_price IS NOT NULL
  AND filled_price > 0;

-- 3. 检查最近平仓订单中价格异常的记录
SELECT
    order_id,
    symbol,
    side,
    status,
    entry_price,
    filled_price,
    exit_price,
    closed_at,
    '平仓订单价格异常' as issue
FROM paper_orders
WHERE status IN ('CLOSED_TP', 'CLOSED_SL', 'CLOSED_BE', 'CLOSED_MANUAL')
  AND closed_at >= datetime('now', '-1 hour')
  AND (
    filled_price IS NULL OR filled_price = 0 OR
    exit_price IS NULL OR exit_price = 0
  );

-- 4. 活跃订单状态统计
SELECT
    status,
    COUNT(*) as total,
    SUM(CASE WHEN filled_price IS NULL OR filled_price = 0 THEN 1 ELSE 0 END) as invalid_count
FROM paper_orders
WHERE status IN ('PENDING', 'OPEN')
GROUP BY status;

-- 5. 检查可能重复的订单（同一交易对+方向，最近创建）
SELECT
    symbol,
    side,
    COUNT(*) as count,
    MIN(created_at) as first_created,
    MAX(created_at) as last_created
FROM paper_orders
WHERE status IN ('PENDING', 'OPEN')
  AND created_at >= datetime('now', '-1 hour')
GROUP BY symbol, side
HAVING COUNT(*) > 1;

-- ============================================================
-- 清理异常订单的 SQL（谨慎执行！）
-- ============================================================

-- 删除 OPEN 状态但成交价无效的订单
-- WARNING: 执行前请先确认上面的查询结果！
-- DELETE FROM paper_orders
-- WHERE status = 'OPEN'
--   AND (filled_price IS NULL OR filled_price = 0);

-- 修复 PENDING 状态但有成交价的订单
-- UPDATE paper_orders
-- SET status = 'OPEN'
-- WHERE status = 'PENDING'
--   AND filled_price IS NOT NULL
--   AND filled_price > 0;
