-- 自动交易系统数据库初始化脚本

CREATE DATABASE IF NOT EXISTS `auto_trade_sys` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE `auto_trade_sys`;

-- 配置表
CREATE TABLE IF NOT EXISTS `trading_config` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `config_key` VARCHAR(100) UNIQUE NOT NULL,
  `config_value` TEXT NOT NULL,
  `config_type` VARCHAR(50) NOT NULL COMMENT 'string, number, boolean, json',
  `category` VARCHAR(50) NOT NULL COMMENT 'position, risk, scan, strategy, api',
  `description` TEXT,
  `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_by` VARCHAR(50),
  INDEX `idx_category` (`category`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='交易配置表';

-- 交易记录表
CREATE TABLE IF NOT EXISTS `trades` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `symbol` VARCHAR(20) NOT NULL,
  `side` VARCHAR(10) NOT NULL COMMENT 'BUY, SELL',
  `quantity` DECIMAL(20, 8) NOT NULL,
  `entry_price` DECIMAL(20, 8) NOT NULL,
  `exit_price` DECIMAL(20, 8),
  `entry_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `exit_time` TIMESTAMP NULL,
  `pnl` DECIMAL(20, 8) DEFAULT 0,
  `pnl_percent` DECIMAL(10, 4) DEFAULT 0,
  `leverage` INT DEFAULT 10,
  `entry_reason` TEXT,
  `exit_reason` VARCHAR(50) COMMENT 'stop_loss, take_profit, trailing_stop, manual',
  `status` VARCHAR(20) DEFAULT 'open' COMMENT 'open, closed, cancelled',
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX `idx_symbol` (`symbol`),
  INDEX `idx_entry_time` (`entry_time`),
  INDEX `idx_status` (`status`),
  INDEX `idx_symbol_status` (`symbol`, `status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='交易记录表';

-- 账户快照表
CREATE TABLE IF NOT EXISTS `account_snapshots` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `total_balance` DECIMAL(20, 8) NOT NULL,
  `available_balance` DECIMAL(20, 8) NOT NULL,
  `total_position_value` DECIMAL(20, 8) DEFAULT 0,
  `total_pnl` DECIMAL(20, 8) DEFAULT 0,
  `open_positions` INT DEFAULT 0,
  `snapshot_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX `idx_snapshot_time` (`snapshot_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='账户快照表';

-- 市场扫描记录表
CREATE TABLE IF NOT EXISTS `market_scans` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `scan_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `symbols_scanned` INT DEFAULT 0,
  `symbols_found` INT DEFAULT 0,
  `top_symbols` JSON,
  `scan_duration` DECIMAL(10, 3) COMMENT '扫描耗时（秒）',
  INDEX `idx_scan_time` (`scan_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='市场扫描记录表';

-- 策略信号表
CREATE TABLE IF NOT EXISTS `trading_signals` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `symbol` VARCHAR(20) NOT NULL,
  `signal_direction` VARCHAR(10) NOT NULL COMMENT 'BUY, SELL',
  `signal_strength` INT NOT NULL COMMENT '0-10',
  `signal_reason` TEXT,
  `rsi` DECIMAL(10, 4),
  `macd_histogram` DECIMAL(20, 8),
  `market_regime` VARCHAR(20) COMMENT 'trending, ranging',
  `signal_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `executed` BOOLEAN DEFAULT FALSE,
  INDEX `idx_symbol` (`symbol`),
  INDEX `idx_signal_time` (`signal_time`),
  INDEX `idx_executed` (`executed`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='交易信号表';

-- 初始化默认配置
INSERT INTO `trading_config` (`config_key`, `config_value`, `config_type`, `category`, `description`) VALUES
-- 仓位控制
('MAX_POSITION_PERCENT', '0.05', 'number', 'position', '单笔最大仓位：账户余额的5%'),
('MAX_TOTAL_POSITION_PERCENT', '0.30', 'number', 'position', '总仓位上限：账户余额的30%'),
('MIN_POSITION_PERCENT', '0.01', 'number', 'position', '单笔最小仓位：账户余额的1%'),

-- 涨跌幅阈值
('MIN_CHANGE_PERCENT', '2.0', 'number', 'scan', '最小涨跌幅阈值：2%'),
('TOP_N_SYMBOLS', '10', 'number', 'scan', '每次扫描后处理的交易对数量（从符合条件的交易对中选择前N个进行详细分析）'),
('MAX_SCAN_SYMBOLS', '500', 'number', 'scan', '扫描的最大交易对数量（0表示扫描所有，建议100-500）'),

-- 风险控制
('STOP_LOSS_PERCENT', '0.03', 'number', 'risk', '止损：3%'),
('TAKE_PROFIT_PERCENT', '0.05', 'number', 'risk', '止盈：5%'),

-- 市场扫描（1小时主周期）
('SCAN_INTERVAL', '3600', 'number', 'scan', '扫描间隔：1小时（秒）'),
('KLINE_INTERVAL', '1h', 'string', 'scan', 'K线周期：1小时'),
('PRIMARY_INTERVAL', '1h', 'string', 'scan', '主周期：1小时'),
('CONFIRM_INTERVAL', '4h', 'string', 'scan', '确认周期：4小时'),
('ENTRY_INTERVAL', '15m', 'string', 'scan', '入场周期：15分钟'),

-- 过滤条件
('MIN_VOLUME_24H', '10000000', 'number', 'scan', '最小24小时成交量：1000万USDT'),
('MIN_VOLATILITY', '0.02', 'number', 'scan', '最小波动率：2%'),

-- 高胜率策略参数
('MIN_SIGNAL_STRENGTH', '5', 'number', 'strategy', '最小信号强度（0-10）'),
('LEVERAGE', '10', 'number', 'strategy', '杠杆倍数'),
('USE_TRAILING_STOP', 'true', 'boolean', 'strategy', '是否使用移动止损'),
('TRAILING_STOP_ACTIVATION', '0.01', 'number', 'strategy', '移动止损激活阈值（盈利1%后激活）'),
('TRAILING_STOP_PROTECT', '0.01', 'number', 'strategy', '移动止损保护利润（保护1%利润）'),


-- API配置
('BINANCE_API_KEY', '', 'string', 'api', '币安API密钥'),
('BINANCE_API_SECRET', '', 'string', 'api', '币安API密钥'),
('USE_TESTNET', 'false', 'boolean', 'api', '是否使用测试网')

ON DUPLICATE KEY UPDATE `config_value` = VALUES(`config_value`);
