-- 币安订单/成交同步表，供定时任务拉取后存储，数据管理从 DB 查询分析
-- 执行: mysql -u user -p db_name < add_binance_sync_tables.sql

USE `auto_trade_sys`;

-- 币安成交记录（userTrades）
CREATE TABLE IF NOT EXISTS `binance_trades` (
  `id` BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  `account_id` INT UNSIGNED NOT NULL,
  `symbol` VARCHAR(32) NOT NULL,
  `trade_id` BIGINT UNSIGNED NOT NULL COMMENT '币安 trade id',
  `order_id` BIGINT UNSIGNED NOT NULL,
  `side` VARCHAR(10) NOT NULL,
  `position_side` VARCHAR(10) DEFAULT NULL,
  `price` DECIMAL(24, 8) NOT NULL,
  `qty` DECIMAL(24, 8) NOT NULL,
  `quote_qty` DECIMAL(24, 8) DEFAULT NULL,
  `realized_pnl` DECIMAL(24, 8) DEFAULT NULL,
  `commission` DECIMAL(24, 8) DEFAULT NULL,
  `commission_asset` VARCHAR(20) DEFAULT NULL,
  `buyer` TINYINT(1) DEFAULT NULL,
  `maker` TINYINT(1) DEFAULT NULL,
  `trade_time` BIGINT UNSIGNED NOT NULL COMMENT '成交时间戳毫秒',
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY `uk_account_trade` (`account_id`, `trade_id`),
  INDEX `idx_account_time` (`account_id`, `trade_time`),
  INDEX `idx_symbol_time` (`account_id`, `symbol`, `trade_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='币安成交记录（定时同步）';

-- 币安订单记录（allOrders）
CREATE TABLE IF NOT EXISTS `binance_orders` (
  `id` BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  `account_id` INT UNSIGNED NOT NULL,
  `symbol` VARCHAR(32) NOT NULL,
  `order_id` BIGINT UNSIGNED NOT NULL,
  `client_order_id` VARCHAR(64) DEFAULT NULL,
  `side` VARCHAR(10) NOT NULL,
  `type` VARCHAR(32) DEFAULT NULL,
  `orig_type` VARCHAR(32) DEFAULT NULL,
  `status` VARCHAR(32) NOT NULL,
  `price` DECIMAL(24, 8) DEFAULT NULL,
  `avg_price` DECIMAL(24, 8) DEFAULT NULL,
  `orig_qty` DECIMAL(24, 8) DEFAULT NULL,
  `executed_qty` DECIMAL(24, 8) DEFAULT NULL,
  `cum_qty` DECIMAL(24, 8) DEFAULT NULL,
  `cum_quote` DECIMAL(24, 8) DEFAULT NULL,
  `stop_price` DECIMAL(24, 8) DEFAULT NULL,
  `reduce_only` TINYINT(1) DEFAULT NULL,
  `position_side` VARCHAR(10) DEFAULT NULL,
  `order_time` BIGINT UNSIGNED NOT NULL COMMENT '下单时间戳毫秒',
  `update_time` BIGINT UNSIGNED DEFAULT NULL COMMENT '更新时间戳毫秒',
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY `uk_account_order` (`account_id`, `order_id`),
  INDEX `idx_account_time` (`account_id`, `order_time`),
  INDEX `idx_symbol_time` (`account_id`, `symbol`, `order_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='币安订单记录（定时同步）';
