From 6b32e761a4054f530c69e5d404427b39994a65fe Mon Sep 17 00:00:00 2001 From: cuizhan <3971687@qq.com> Date: Wed, 13 Aug 2025 17:18:54 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=E5=AE=8C=E6=95=B4?= =?UTF-8?q?=E7=9A=84=E8=82=A1=E7=A5=A8=E4=BA=A4=E6=98=93=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增交易相关枚举类型 (TradeDirection, OrderType, OrderStatus) - 新增交易数据模型 trade_models.py (委托表、成交表) - 新增独立交易管理器 stocktrade_manager.py * 委托记录和成交记录功能 * 状态更新和查询功能 * 交易汇总统计功能 - 新增交易系统使用示例 trade_example.py - 新增完整测试脚本 test_stocktrade.py - 完善 common.py 的交易字段约定 功能特点: 完整的订单成交状态更新流程 独立的交易记录模块架构 统一的 stockcode 字段命名 毫秒级时间戳记录 灵活的查询和统计功能 完善的测试验证 --- src/data_process_model/common.py | 36 ++ src/data_process_model/stocktrade_manager.py | 471 +++++++++++++++++++ src/data_process_model/test_stocktrade.py | 205 ++++++++ src/data_process_model/trade_example.py | 263 +++++++++++ src/data_process_model/trade_models.py | 118 +++++ 5 files changed, 1093 insertions(+) create mode 100644 src/data_process_model/stocktrade_manager.py create mode 100644 src/data_process_model/test_stocktrade.py create mode 100644 src/data_process_model/trade_example.py create mode 100644 src/data_process_model/trade_models.py diff --git a/src/data_process_model/common.py b/src/data_process_model/common.py index 92f9a99..be805ef 100644 --- a/src/data_process_model/common.py +++ b/src/data_process_model/common.py @@ -44,6 +44,26 @@ class DataSource(Enum): CALCULATED = "calculated" # 计算生成数据 REALTIME = "realtime" # 实时数据 +# 交易方向 +class TradeDirection(Enum): + """交易方向枚举""" + BUY = "BUY" + SELL = "SELL" + +# 委托类型 +class OrderType(Enum): + """委托类型枚举""" + MARKET = "MARKET" # 市价单 + LIMIT = "LIMIT" # 限价单 + +# 委托状态 +class OrderStatus(Enum): + """委托状态枚举""" + PENDING = "PENDING" # 待成交 + FILLED = "FILLED" # 全部成交 + PARTIAL = "PARTIAL" # 部分成交 + CANCELLED = "CANCELLED" # 已撤销 + # ============================= 数据结构约定 ============================= # 标准K线数据字段名约定 @@ -56,6 +76,22 @@ KLINE_COLUMNS = { 'volume': 'volume', # 成交量 (int) } +# 交易记录相关字段名约定 +TRADE_COLUMNS = { + 'order_id': 'order_id', + 'execution_id': 'execution_id', + 'stockcode': 'stockcode', # 统一使用 stockcode + 'order_time': 'order_time', + 'execution_time': 'execution_time', + 'direction': 'direction', + 'price': 'price', + 'quantity': 'quantity', + 'amount': 'amount', + 'commission': 'commission', + 'order_type': 'order_type', + 'status': 'status' +} + # 标准K线数据字段类型约定 KLINE_DTYPES = { 'timestamp': 'datetime64[ns]', diff --git a/src/data_process_model/stocktrade_manager.py b/src/data_process_model/stocktrade_manager.py new file mode 100644 index 0000000..e4d0794 --- /dev/null +++ b/src/data_process_model/stocktrade_manager.py @@ -0,0 +1,471 @@ +""" +股票交易管理器 - 独立的交易记录模块 +专门负责交易委托和成交记录的管理 +与 stockdata_manager.py 并行存在,职责分离 +""" + +import uuid +import logging +from typing import Dict, List, Any, Optional +from datetime import datetime + +# 复用现有架构组件 +from database_manager import get_database_manager +from trade_models import TradeOrder, TradeExecution, create_trade_tables +from common import ( + LOG_PREFIXES, + TradeDirection, OrderType, OrderStatus +) + +logger = logging.getLogger(__name__) + +class StockTradeManager: + """ + 股票交易管理器 + + 职责: + 1. 记录交易委托信息 + 2. 记录交易成交信息 + 3. 提供交易记录查询功能 + 4. 管理交易相关数据表 + """ + + def __init__(self): + """初始化交易管理器""" + self.db_manager = get_database_manager() + self._setup_trade_tables() + logger.info(f"{LOG_PREFIXES['SUCCESS']} 股票交易管理器初始化完成") + + def _setup_trade_tables(self): + """设置交易数据表""" + try: + results = create_trade_tables() + success_count = sum(results.values()) + total_count = len(results) + print(f"{LOG_PREFIXES['DATABASE']} 交易表创建: {success_count}/{total_count} 成功") + except Exception as e: + print(f"{LOG_PREFIXES['ERROR']} 交易表创建失败: {e}") + + # ================================ 核心功能 ================================ + + def record_order(self, order_info: Dict[str, Any]) -> str: + """ + 记录交易委托 + + Args: + order_info: 委托信息字典 + - strategy_id: 策略ID + - stockcode: 股票代码 + - direction: 交易方向 (BUY/SELL) + - order_type: 委托类型 (MARKET/LIMIT) + - quantity: 委托数量 + - price: 委托价格 (限价单必填) + - notes: 备注 (可选) + + Returns: + str: 委托ID + + Example: + >>> order_info = { + >>> 'strategy_id': 'my_strategy', + >>> 'stockcode': '601658.SH', + >>> 'direction': 'BUY', + >>> 'order_type': 'MARKET', + >>> 'quantity': 100 + >>> } + >>> order_id = trade_manager.record_order(order_info) + """ + try: + # 生成唯一订单ID + order_id = f"ORDER_{datetime.now().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}" + + # 验证必填字段 + required_fields = ['strategy_id', 'stockcode', 'direction', 'order_type', 'quantity'] + for field in required_fields: + if field not in order_info: + raise ValueError(f"缺少必填字段: {field}") + + # 验证枚举值 + if order_info['direction'] not in [TradeDirection.BUY.value, TradeDirection.SELL.value]: + raise ValueError(f"无效的交易方向: {order_info['direction']}") + + if order_info['order_type'] not in [OrderType.MARKET.value, OrderType.LIMIT.value]: + raise ValueError(f"无效的委托类型: {order_info['order_type']}") + + # 限价单必须提供价格 + if order_info['order_type'] == OrderType.LIMIT.value and 'price' not in order_info: + raise ValueError("限价单必须提供委托价格") + + # 创建委托记录 + order_data = { + 'order_id': order_id, + 'strategy_id': order_info['strategy_id'], + 'stockcode': order_info['stockcode'], + 'direction': order_info['direction'], + 'order_type': order_info['order_type'], + 'quantity': order_info['quantity'], + 'price': order_info.get('price'), + 'status': OrderStatus.PENDING.value, + 'notes': order_info.get('notes', ''), + 'order_time': datetime.now() + } + + # 保存到数据库 + TradeOrder.create(**order_data) + + print(f"{LOG_PREFIXES['SUCCESS']} 记录委托 {order_id}: {order_info['stockcode']} {order_info['direction']} {order_info['quantity']}") + return order_id + + except Exception as e: + print(f"{LOG_PREFIXES['ERROR']} 记录委托失败: {e}") + raise + + def record_execution(self, exec_info: Dict[str, Any]) -> str: + """ + 记录交易成交 + + Args: + exec_info: 成交信息字典 + - order_id: 对应的委托ID + - stockcode: 股票代码 + - price: 成交价格 + - quantity: 成交数量 + - execution_time: 成交时间 (可选,默认当前时间) + - commission: 手续费 (可选,默认0) + - notes: 备注 (可选) + + Returns: + str: 成交ID + + Example: + >>> exec_info = { + >>> 'order_id': order_id, + >>> 'stockcode': '601658.SH', + >>> 'price': 10.50, + >>> 'quantity': 100 + >>> } + >>> exec_id = trade_manager.record_execution(exec_info) + """ + try: + # 生成唯一成交ID + exec_id = f"EXEC_{datetime.now().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}" + + # 验证必填字段 + required_fields = ['order_id', 'stockcode', 'price', 'quantity'] + for field in required_fields: + if field not in exec_info: + raise ValueError(f"缺少必填字段: {field}") + + # 查找对应的委托记录 + try: + order = TradeOrder.get(TradeOrder.order_id == exec_info['order_id']) + except Exception: + raise ValueError(f"未找到对应的委托记录: {exec_info['order_id']}") + + # 计算成交金额 + amount = float(exec_info['price']) * int(exec_info['quantity']) + + # 创建成交记录 + exec_data = { + 'execution_id': exec_id, + 'order_id': exec_info['order_id'], + 'stockcode': exec_info['stockcode'], + 'price': exec_info['price'], + 'quantity': exec_info['quantity'], + 'amount': amount, + 'commission': exec_info.get('commission', 0), + 'direction': order.direction, + 'notes': exec_info.get('notes', ''), + 'execution_time': exec_info.get('execution_time', datetime.now()) + } + + # 保存到数据库 + TradeExecution.create(**exec_data) + + print(f"{LOG_PREFIXES['SUCCESS']} 记录成交 {exec_id}: {exec_info['stockcode']} {order.direction} {exec_info['quantity']}@{exec_info['price']}") + return exec_id + + except Exception as e: + print(f"{LOG_PREFIXES['ERROR']} 记录成交失败: {e}") + raise + + def update_order_status(self, order_id: str, status: str) -> bool: + """ + 更新委托状态 + + Args: + order_id: 委托ID + status: 新状态 (PENDING/FILLED/CANCELLED/PARTIAL) + + Returns: + bool: 更新是否成功 + """ + try: + # 验证状态值 + valid_statuses = [s.value for s in OrderStatus] + if status not in valid_statuses: + raise ValueError(f"无效的委托状态: {status}") + + # 更新状态 + query = TradeOrder.update( + status=status, + updated_at=datetime.now() + ).where(TradeOrder.order_id == order_id) + + updated_count = query.execute() + + if updated_count > 0: + print(f"{LOG_PREFIXES['SUCCESS']} 更新委托状态: {order_id} -> {status}") + return True + else: + print(f"{LOG_PREFIXES['WARNING']} 未找到委托记录: {order_id}") + return False + + except Exception as e: + print(f"{LOG_PREFIXES['ERROR']} 更新委托状态失败: {e}") + return False + + def get_orders(self, filters: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]: + """ + 查询委托记录 + + Args: + filters: 过滤条件字典 + - stockcode: 股票代码 + - strategy_id: 策略ID + - status: 委托状态 + - start_date: 开始日期 + - end_date: 结束日期 + - limit: 返回条数限制 + + Returns: + List[Dict]: 委托记录列表 + """ + try: + query = TradeOrder.select() + + if filters: + if 'stockcode' in filters: + query = query.where(TradeOrder.stockcode == filters['stockcode']) + + if 'strategy_id' in filters: + query = query.where(TradeOrder.strategy_id == filters['strategy_id']) + + if 'status' in filters: + query = query.where(TradeOrder.status == filters['status']) + + if 'start_date' in filters: + query = query.where(TradeOrder.order_time >= filters['start_date']) + + if 'end_date' in filters: + query = query.where(TradeOrder.order_time <= filters['end_date']) + + if 'limit' in filters: + query = query.limit(filters['limit']) + + # 按时间倒序排列 + query = query.order_by(TradeOrder.order_time.desc()) + + # 转换为字典列表 + orders = [] + for order in query: + orders.append({ + 'order_id': order.order_id, + 'strategy_id': order.strategy_id, + 'stockcode': order.stockcode, + 'order_time': order.order_time, + 'direction': order.direction, + 'order_type': order.order_type, + 'quantity': order.quantity, + 'price': float(order.price) if order.price else None, + 'status': order.status, + 'notes': order.notes + }) + + return orders + + except Exception as e: + print(f"{LOG_PREFIXES['ERROR']} 查询委托记录失败: {e}") + return [] + + def get_executions(self, filters: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]: + """ + 查询成交记录 + + Args: + filters: 过滤条件字典 + - stockcode: 股票代码 + - order_id: 委托ID + - direction: 交易方向 + - start_date: 开始日期 + - end_date: 结束日期 + - limit: 返回条数限制 + + Returns: + List[Dict]: 成交记录列表 + """ + try: + query = TradeExecution.select() + + if filters: + if 'stockcode' in filters: + query = query.where(TradeExecution.stockcode == filters['stockcode']) + + if 'order_id' in filters: + query = query.where(TradeExecution.order_id == filters['order_id']) + + if 'direction' in filters: + query = query.where(TradeExecution.direction == filters['direction']) + + if 'start_date' in filters: + query = query.where(TradeExecution.execution_time >= filters['start_date']) + + if 'end_date' in filters: + query = query.where(TradeExecution.execution_time <= filters['end_date']) + + if 'limit' in filters: + query = query.limit(filters['limit']) + + # 按时间倒序排列 + query = query.order_by(TradeExecution.execution_time.desc()) + + # 转换为字典列表 + executions = [] + for execution in query: + executions.append({ + 'execution_id': execution.execution_id, + 'order_id': execution.order_id, + 'stockcode': execution.stockcode, + 'execution_time': execution.execution_time, + 'price': float(execution.price), + 'quantity': execution.quantity, + 'amount': float(execution.amount), + 'commission': float(execution.commission), + 'direction': execution.direction, + 'notes': execution.notes + }) + + return executions + + except Exception as e: + print(f"{LOG_PREFIXES['ERROR']} 查询成交记录失败: {e}") + return [] + + def get_trade_summary(self, stockcode: Optional[str] = None, strategy_id: Optional[str] = None) -> Dict[str, Any]: + """ + 获取交易汇总信息 + + Args: + stockcode: 股票代码 (可选) + strategy_id: 策略ID (可选) + + Returns: + Dict: 交易汇总信息 + """ + try: + summary = { + 'total_orders': 0, + 'total_executions': 0, + 'total_amount': 0.0, + 'total_commission': 0.0, + 'buy_count': 0, + 'sell_count': 0, + 'pending_orders': 0 + } + + # 统计委托 + order_query = TradeOrder.select() + if stockcode: + order_query = order_query.where(TradeOrder.stockcode == stockcode) + if strategy_id: + order_query = order_query.where(TradeOrder.strategy_id == strategy_id) + + summary['total_orders'] = order_query.count() + summary['pending_orders'] = order_query.where(TradeOrder.status == OrderStatus.PENDING.value).count() + + # 统计成交 + exec_query = TradeExecution.select() + if stockcode: + exec_query = exec_query.where(TradeExecution.stockcode == stockcode) + + summary['total_executions'] = exec_query.count() + summary['buy_count'] = exec_query.where(TradeExecution.direction == TradeDirection.BUY.value).count() + summary['sell_count'] = exec_query.where(TradeExecution.direction == TradeDirection.SELL.value).count() + + # 统计金额 + for execution in exec_query: + summary['total_amount'] += float(execution.amount) + summary['total_commission'] += float(execution.commission) + + return summary + + except Exception as e: + print(f"{LOG_PREFIXES['ERROR']} 获取交易汇总失败: {e}") + return {} + + def close(self): + """关闭交易管理器""" + # 注意:database_manager 可能没有 close 方法,先检查 + try: + if hasattr(self.db_manager, 'close') and callable(getattr(self.db_manager, 'close')): + getattr(self.db_manager, 'close')() + except Exception as e: + print(f"{LOG_PREFIXES['WARNING']} 关闭数据库管理器时出错: {e}") + + print(f"{LOG_PREFIXES['DATABASE']} 交易管理器已关闭") + +# 工厂函数,与 stockdata_manager.py 保持一致的模式 +def get_stock_trade_manager() -> StockTradeManager: + """获取股票交易管理器实例""" + return StockTradeManager() + +if __name__ == "__main__": + # 测试交易管理器 + print("测试股票交易管理器...") + + trade_manager = get_stock_trade_manager() + + # 测试记录委托 + order_info = { + 'strategy_id': 'test_strategy', + 'stockcode': '601658.SH', + 'direction': 'BUY', + 'order_type': 'MARKET', + 'quantity': 100, + 'notes': '测试委托' + } + + try: + order_id = trade_manager.record_order(order_info) + print(f"委托ID: {order_id}") + + # 测试记录成交 + exec_info = { + 'order_id': order_id, + 'stockcode': '601658.SH', + 'price': 10.50, + 'quantity': 100, + 'commission': 5.0 + } + + exec_id = trade_manager.record_execution(exec_info) + print(f"成交ID: {exec_id}") + + # 更新委托状态 + trade_manager.update_order_status(order_id, 'FILLED') + + # 查询记录 + orders = trade_manager.get_orders({'limit': 5}) + print(f"最近委托: {len(orders)} 条") + + executions = trade_manager.get_executions({'limit': 5}) + print(f"最近成交: {len(executions)} 条") + + # 交易汇总 + summary = trade_manager.get_trade_summary() + print(f"交易汇总: {summary}") + + except Exception as e: + print(f"测试失败: {e}") + finally: + trade_manager.close() diff --git a/src/data_process_model/test_stocktrade.py b/src/data_process_model/test_stocktrade.py new file mode 100644 index 0000000..e553263 --- /dev/null +++ b/src/data_process_model/test_stocktrade.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +""" +测试股票交易管理器功能 +""" + +import sys +import os + +# 添加当前目录到Python路径 +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +def test_imports(): + """测试模块导入""" + print("=" * 50) + print("测试模块导入...") + + try: + from common import TradeDirection, OrderType, OrderStatus + print("✓ common 模块导入成功") + except Exception as e: + print(f"✗ common 模块导入失败: {e}") + return False + + try: + from database_manager import get_database_manager + print("✓ database_manager 模块导入成功") + except Exception as e: + print(f"✗ database_manager 模块导入失败: {e}") + return False + + try: + from trade_models import TradeOrder, TradeExecution, create_trade_tables + print("✓ trade_models 模块导入成功") + except Exception as e: + print(f"✗ trade_models 模块导入失败: {e}") + return False + + try: + from stocktrade_manager import StockTradeManager, get_stock_trade_manager + print("✓ stocktrade_manager 模块导入成功") + except Exception as e: + print(f"✗ stocktrade_manager 模块导入失败: {e}") + return False + + return True + +def test_manager_creation(): + """测试管理器创建""" + print("=" * 50) + print("测试管理器创建...") + + try: + from stocktrade_manager import get_stock_trade_manager + manager = get_stock_trade_manager() + print("✓ 交易管理器创建成功") + return manager + except Exception as e: + print(f"✗ 交易管理器创建失败: {e}") + return None + +def test_order_recording(manager): + """测试委托记录功能""" + print("=" * 50) + print("测试委托记录功能...") + + try: + # 准备委托信息 + order_info = { + 'strategy_id': 'test_strategy_001', + 'stockcode': '000001.SZ', + 'direction': 'BUY', + 'order_type': 'MARKET', + 'quantity': 100, + 'notes': '测试市价买入委托' + } + + # 记录委托 + order_id = manager.record_order(order_info) + print(f"✓ 委托记录成功,订单ID: {order_id}") + return order_id + + except Exception as e: + print(f"✗ 委托记录失败: {e}") + return None + +def test_execution_recording(manager, order_id): + """测试成交记录功能""" + print("=" * 50) + print("测试成交记录功能...") + + if not order_id: + print("✗ 无有效订单ID,跳过成交记录测试") + return None + + try: + # 准备成交信息 + exec_info = { + 'order_id': order_id, + 'stockcode': '000001.SZ', + 'price': 12.50, + 'quantity': 100, + 'commission': 5.0, + 'notes': '测试成交记录' + } + + # 记录成交 + exec_id = manager.record_execution(exec_info) + print(f"✓ 成交记录成功,成交ID: {exec_id}") + return exec_id + + except Exception as e: + print(f"✗ 成交记录失败: {e}") + return None + +def test_status_update(manager, order_id): + """测试状态更新功能""" + print("=" * 50) + print("测试状态更新功能...") + + if not order_id: + print("✗ 无有效订单ID,跳过状态更新测试") + return False + + try: + # 更新订单状态为已成交 + result = manager.update_order_status(order_id, 'FILLED') + if result: + print("✓ 订单状态更新成功") + else: + print("✗ 订单状态更新失败") + return result + + except Exception as e: + print(f"✗ 订单状态更新异常: {e}") + return False + +def test_query_functions(manager): + """测试查询功能""" + print("=" * 50) + print("测试查询功能...") + + try: + # 查询最近的委托记录 + orders = manager.get_orders({'limit': 5}) + print(f"✓ 查询委托记录成功,找到 {len(orders)} 条记录") + + # 查询最近的成交记录 + executions = manager.get_executions({'limit': 5}) + print(f"✓ 查询成交记录成功,找到 {len(executions)} 条记录") + + # 获取交易汇总 + summary = manager.get_trade_summary() + print(f"✓ 交易汇总获取成功,总委托: {summary.get('total_orders', 0)}, 总成交: {summary.get('total_executions', 0)}") + + return True + + except Exception as e: + print(f"✗ 查询功能测试失败: {e}") + return False + +def main(): + """主测试函数""" + print("开始测试股票交易管理器功能") + print("当前工作目录:", os.getcwd()) + + # 测试模块导入 + if not test_imports(): + print("\n❌ 模块导入测试失败,停止测试") + return + + # 测试管理器创建 + manager = test_manager_creation() + if not manager: + print("\n❌ 管理器创建测试失败,停止测试") + return + + try: + # 测试委托记录 + order_id = test_order_recording(manager) + + # 测试成交记录 + exec_id = test_execution_recording(manager, order_id) + + # 测试状态更新 + test_status_update(manager, order_id) + + # 测试查询功能 + test_query_functions(manager) + + print("=" * 50) + print("✅ 所有测试完成") + + except Exception as e: + print(f"\n❌ 测试过程中发生异常: {e}") + + finally: + # 关闭管理器 + try: + manager.close() + print("🔒 交易管理器已关闭") + except Exception as e: + print(f"⚠️ 关闭管理器时出错: {e}") + +if __name__ == "__main__": + main() diff --git a/src/data_process_model/trade_example.py b/src/data_process_model/trade_example.py new file mode 100644 index 0000000..0be9655 --- /dev/null +++ b/src/data_process_model/trade_example.py @@ -0,0 +1,263 @@ +""" +交易记录系统使用示例 +演示如何在策略中使用 stocktrade_manager.py 记录交易 +""" + +from datetime import datetime +from typing import Optional +from stocktrade_manager import get_stock_trade_manager +from stockdata_manager import get_stock_data_manager + +class SimpleTradeStrategy: + """ + 简单交易策略示例 + 演示如何集成交易记录功能 + """ + + def __init__(self, strategy_id: str): + self.strategy_id = strategy_id + + # 数据管理器和交易管理器并行使用 + self.data_manager = get_stock_data_manager() # 负责K线数据 + self.trade_manager = get_stock_trade_manager() # 负责交易记录 + + print(f"✅ 策略 {strategy_id} 初始化完成") + + def execute_buy_signal(self, stockcode: str, quantity: int, price: Optional[float] = None): + """ + 执行买入信号 + + Args: + stockcode: 股票代码 + quantity: 买入数量 + price: 限价(None表示市价单) + """ + try: + print(f"\n📈 执行买入信号: {stockcode} x {quantity}") + + # 1. 记录委托 + order_info = { + 'strategy_id': self.strategy_id, + 'stockcode': stockcode, + 'direction': 'BUY', + 'order_type': 'LIMIT' if price else 'MARKET', + 'quantity': quantity, + 'notes': f'策略买入信号 - {datetime.now().strftime("%H:%M:%S")}' + } + + if price: + order_info['price'] = price + + order_id = self.trade_manager.record_order(order_info) + print(f"🎯 委托已提交: {order_id}") + + # 2. 模拟交易执行(实际应用中这里会调用券商API) + execution_price = price if price else self._get_current_price(stockcode) + execution_result = self._simulate_execution(stockcode, quantity, execution_price) + + # 3. 记录成交 + if execution_result['success']: + exec_info = { + 'order_id': order_id, + 'stockcode': stockcode, + 'price': execution_result['price'], + 'quantity': execution_result['quantity'], + 'commission': execution_result['commission'], + 'notes': '模拟成交' + } + + exec_id = self.trade_manager.record_execution(exec_info) + print(f"✅ 成交记录: {exec_id}") + + # 4. 更新委托状态 + self.trade_manager.update_order_status(order_id, 'FILLED') + + return { + 'order_id': order_id, + 'execution_id': exec_id, + 'success': True + } + else: + print(f"❌ 交易执行失败: {execution_result['error']}") + self.trade_manager.update_order_status(order_id, 'CANCELLED') + return {'success': False, 'error': execution_result['error']} + + except Exception as e: + print(f"❌ 执行买入信号失败: {e}") + return {'success': False, 'error': str(e)} + + def execute_sell_signal(self, stockcode: str, quantity: int, price: Optional[float] = None): + """ + 执行卖出信号 + + Args: + stockcode: 股票代码 + quantity: 卖出数量 + price: 限价(None表示市价单) + """ + try: + print(f"\n📉 执行卖出信号: {stockcode} x {quantity}") + + # 1. 记录委托 + order_info = { + 'strategy_id': self.strategy_id, + 'stockcode': stockcode, + 'direction': 'SELL', + 'order_type': 'LIMIT' if price else 'MARKET', + 'quantity': quantity, + 'notes': f'策略卖出信号 - {datetime.now().strftime("%H:%M:%S")}' + } + + if price: + order_info['price'] = price + + order_id = self.trade_manager.record_order(order_info) + print(f"🎯 委托已提交: {order_id}") + + # 2. 模拟交易执行 + execution_price = price if price else self._get_current_price(stockcode) + execution_result = self._simulate_execution(stockcode, quantity, execution_price) + + # 3. 记录成交 + if execution_result['success']: + exec_info = { + 'order_id': order_id, + 'stockcode': stockcode, + 'price': execution_result['price'], + 'quantity': execution_result['quantity'], + 'commission': execution_result['commission'], + 'notes': '模拟成交' + } + + exec_id = self.trade_manager.record_execution(exec_info) + print(f"✅ 成交记录: {exec_id}") + + # 4. 更新委托状态 + self.trade_manager.update_order_status(order_id, 'FILLED') + + return { + 'order_id': order_id, + 'execution_id': exec_id, + 'success': True + } + else: + print(f"❌ 交易执行失败: {execution_result['error']}") + self.trade_manager.update_order_status(order_id, 'CANCELLED') + return {'success': False, 'error': execution_result['error']} + + except Exception as e: + print(f"❌ 执行卖出信号失败: {e}") + return {'success': False, 'error': str(e)} + + def _get_current_price(self, stockcode: str) -> float: + """ + 获取当前股价(模拟) + 实际应用中会从数据源获取实时价格 + """ + # 这里使用模拟价格,实际应用中会调用数据接口 + price_map = { + '601658.SH': 10.50, + '601398.SH': 5.20, + '601288.SH': 42.80, + '510310.SH': 1.05 + } + return price_map.get(stockcode, 10.0) + + def _simulate_execution(self, stockcode: str, quantity: int, price: float) -> dict: + """ + 模拟交易执行 + 实际应用中会调用券商API + """ + # 模拟成功执行 + commission = max(5.0, quantity * price * 0.0003) # 最低5元手续费 + + return { + 'success': True, + 'price': price, + 'quantity': quantity, + 'commission': round(commission, 2) + } + + def get_strategy_performance(self) -> dict: + """获取策略绩效统计""" + return self.trade_manager.get_trade_summary(strategy_id=self.strategy_id) + + def get_recent_trades(self, limit: int = 10) -> dict: + """获取最近的交易记录""" + orders = self.trade_manager.get_orders({ + 'strategy_id': self.strategy_id, + 'limit': limit + }) + + executions = self.trade_manager.get_executions({ + 'limit': limit + }) + + return { + 'orders': orders, + 'executions': executions + } + + def close(self): + """关闭策略""" + self.data_manager.close() + self.trade_manager.close() + print(f"🔒 策略 {self.strategy_id} 已关闭") + +def demo_trading_strategy(): + """ + 演示交易策略的完整流程 + """ + print("🚀 开始演示交易记录系统...") + + # 创建策略实例 + strategy = SimpleTradeStrategy("demo_strategy_001") + + try: + # 模拟交易信号 + print("\n" + "="*50) + print("📊 模拟交易场景") + print("="*50) + + # 买入信号 + result1 = strategy.execute_buy_signal('601658.SH', 100, 10.50) + result2 = strategy.execute_buy_signal('601398.SH', 200) # 市价单 + + # 卖出信号 + result3 = strategy.execute_sell_signal('601658.SH', 50, 10.80) + + # 查看交易记录 + print("\n" + "="*50) + print("📈 交易记录查询") + print("="*50) + + recent_trades = strategy.get_recent_trades(5) + print(f"📋 最近委托 ({len(recent_trades['orders'])} 条):") + for order in recent_trades['orders']: + print(f" {order['order_time']} | {order['stockcode']} | {order['direction']} | {order['quantity']} | {order['status']}") + + print(f"\n✅ 最近成交 ({len(recent_trades['executions'])} 条):") + for execution in recent_trades['executions']: + print(f" {execution['execution_time']} | {execution['stockcode']} | {execution['direction']} | {execution['quantity']}@{execution['price']}") + + # 策略绩效 + print("\n" + "="*50) + print("📊 策略绩效统计") + print("="*50) + + performance = strategy.get_strategy_performance() + print(f"总委托数: {performance.get('total_orders', 0)}") + print(f"总成交数: {performance.get('total_executions', 0)}") + print(f"买入次数: {performance.get('buy_count', 0)}") + print(f"卖出次数: {performance.get('sell_count', 0)}") + print(f"总成交金额: {performance.get('total_amount', 0):.2f}") + print(f"总手续费: {performance.get('total_commission', 0):.2f}") + print(f"待成交委托: {performance.get('pending_orders', 0)}") + + except Exception as e: + print(f"❌ 演示过程中出错: {e}") + finally: + strategy.close() + +if __name__ == "__main__": + demo_trading_strategy() diff --git a/src/data_process_model/trade_models.py b/src/data_process_model/trade_models.py new file mode 100644 index 0000000..21f5bc2 --- /dev/null +++ b/src/data_process_model/trade_models.py @@ -0,0 +1,118 @@ +""" +交易数据模型 - 基于现有 stock_models.py 的架构 +定义交易委托和成交的数据表结构 +""" + +from peewee import ( + Model, MySQLDatabase, CharField, DateTimeField, + IntegerField, DecimalField, TextField +) +from datetime import datetime +from database_config import DATABASE_CONFIG + +# 复用现有的数据库连接方式 +database = MySQLDatabase(**DATABASE_CONFIG) + +class BaseTradeModel(Model): + """交易数据基础模型""" + class Meta: + database = database + +class TradeOrder(BaseTradeModel): + """ + 交易委托模型 + 记录交易委托的详细信息 + """ + order_id = CharField(primary_key=True, max_length=50, help_text="委托唯一ID") + strategy_id = CharField(max_length=50, help_text="策略ID") + stockcode = CharField(max_length=20, help_text="股票代码") + order_time = DateTimeField(default=datetime.now, help_text="委托时间") + direction = CharField(max_length=10, help_text="交易方向 BUY/SELL") + order_type = CharField(max_length=10, help_text="委托类型 MARKET/LIMIT") + quantity = IntegerField(help_text="委托数量") + price = DecimalField(max_digits=10, decimal_places=3, null=True, help_text="委托价格") + status = CharField(max_length=20, default='PENDING', help_text="委托状态") + notes = TextField(null=True, help_text="备注信息") + created_at = DateTimeField(default=datetime.now, help_text="记录创建时间") + updated_at = DateTimeField(default=datetime.now, help_text="记录更新时间") + + class Meta: + table_name = 'trade_orders' + indexes = ( + # 复合索引优化查询性能 + (('stockcode', 'order_time'), False), + (('strategy_id', 'order_time'), False), + (('status', 'order_time'), False), + ) + +class TradeExecution(BaseTradeModel): + """ + 交易成交模型 + 记录交易成交的详细信息 + """ + execution_id = CharField(primary_key=True, max_length=50, help_text="成交唯一ID") + order_id = CharField(max_length=50, help_text="对应的委托ID") + stockcode = CharField(max_length=20, help_text="股票代码") + execution_time = DateTimeField(default=datetime.now, help_text="成交时间") + price = DecimalField(max_digits=10, decimal_places=3, help_text="成交价格") + quantity = IntegerField(help_text="成交数量") + amount = DecimalField(max_digits=15, decimal_places=2, help_text="成交金额") + commission = DecimalField(max_digits=10, decimal_places=2, default=0, help_text="手续费") + direction = CharField(max_length=10, help_text="交易方向 BUY/SELL") + notes = TextField(null=True, help_text="备注信息") + created_at = DateTimeField(default=datetime.now, help_text="记录创建时间") + + class Meta: + table_name = 'trade_executions' + indexes = ( + # 复合索引优化查询性能 + (('stockcode', 'execution_time'), False), + (('order_id', 'execution_time'), False), + (('direction', 'execution_time'), False), + ) + +def create_trade_tables(): + """ + 创建交易相关数据表 + + Returns: + dict: 创建结果 {table_name: success} + """ + results = {} + + try: + # 连接数据库 + database.connect() + + # 创建委托表 + try: + database.create_tables([TradeOrder], safe=True) + results['trade_orders'] = True + print("✅ 创建交易委托表 trade_orders 成功") + except Exception as e: + results['trade_orders'] = False + print(f"❌ 创建交易委托表失败: {e}") + + # 创建成交表 + try: + database.create_tables([TradeExecution], safe=True) + results['trade_executions'] = True + print("✅ 创建交易成交表 trade_executions 成功") + except Exception as e: + results['trade_executions'] = False + print(f"❌ 创建交易成交表失败: {e}") + + except Exception as e: + print(f"❌ 数据库连接失败: {e}") + results['connection'] = False + finally: + if not database.is_closed(): + database.close() + + return results + +if __name__ == "__main__": + # 测试创建表 + print("开始创建交易数据表...") + results = create_trade_tables() + print(f"创建结果: {results}")