live_trade.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/env python3
  2. """
  3. 实盘交易执行脚本
  4. 连接券商API(QMT/Ptrade)执行实际交易
  5. """
  6. import json
  7. import logging
  8. from datetime import datetime
  9. from typing import Dict, List
  10. import sys
  11. # 配置日志
  12. logging.basicConfig(
  13. level=logging.INFO,
  14. format='%(asctime)s - %(levelname)s - %(message)s',
  15. handlers=[
  16. logging.FileHandler('live_trade.log', encoding='utf-8'),
  17. logging.StreamHandler()
  18. ]
  19. )
  20. logger = logging.getLogger(__name__)
  21. class TradeExecutor:
  22. """交易执行器"""
  23. def __init__(self, broker_api=None):
  24. self.broker_api = broker_api # 券商API实例
  25. self.simulation_mode = True # 默认模拟模式
  26. def connect(self, config: Dict):
  27. """连接券商API"""
  28. # 这里接入QMT或Ptrade的API
  29. # from xtquant import xtdata, xttype, xttrader
  30. logger.info("连接交易API...")
  31. if self.simulation_mode:
  32. logger.info("当前为模拟交易模式,不会执行真实交易")
  33. else:
  34. logger.info("已连接真实交易接口")
  35. def buy(self, code: str, name: str, price: float, amount: float,
  36. strategy: str) -> bool:
  37. """买入"""
  38. shares = int(amount / price / 100) * 100 # 整手
  39. if shares < 100:
  40. logger.warning(f"{name}({code}) 资金不足,无法买入")
  41. return False
  42. logger.info(f"[BUY] {name}({code}): {shares}股 @ {price:.2f}, 策略:{strategy}")
  43. if not self.simulation_mode:
  44. # 执行真实交易
  45. # order_id = self.broker_api.buy(code, shares, price)
  46. pass
  47. return True
  48. def sell(self, code: str, name: str, price: float, shares: int,
  49. reason: str, strategy: str) -> bool:
  50. """卖出"""
  51. logger.info(f"[SELL] {name}({code}): {shares}股 @ {price:.2f}, 原因:{reason}, 策略:{strategy}")
  52. if not self.simulation_mode:
  53. # 执行真实交易
  54. # order_id = self.broker_api.sell(code, shares, price)
  55. pass
  56. return True
  57. def get_positions(self) -> Dict:
  58. """获取当前持仓"""
  59. # 从券商API获取持仓
  60. return {}
  61. def get_account(self) -> Dict:
  62. """获取账户信息"""
  63. return {
  64. 'total_asset': 1000000,
  65. 'available_cash': 100000,
  66. 'market_value': 900000
  67. }
  68. class LiveTrader:
  69. """实盘交易主类"""
  70. def __init__(self, config_path: str = "config.json"):
  71. self.config = self.load_config(config_path)
  72. self.executor = TradeExecutor()
  73. self.executor.simulation_mode = True # 安全第一,默认模拟
  74. def load_config(self, path: str) -> Dict:
  75. """加载配置"""
  76. try:
  77. with open(path, 'r', encoding='utf-8') as f:
  78. return json.load(f)
  79. except Exception as e:
  80. logger.error(f"加载配置失败: {e}")
  81. return {}
  82. def run_daily(self):
  83. """每日执行"""
  84. logger.info("=" * 60)
  85. logger.info("开始实盘交易")
  86. logger.info(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  87. logger.info("=" * 60)
  88. # 1. 获取账户状态
  89. account = self.executor.get_account()
  90. logger.info(f"账户总资产: {account['total_asset']:,.0f}")
  91. logger.info(f"可用资金: {account['available_cash']:,.0f}")
  92. # 2. 获取当前持仓
  93. positions = self.executor.get_positions()
  94. # 3. 检查风险
  95. # risk_check()
  96. # 4. 执行策略信号
  97. # 这里调用quant_system.py中的策略逻辑
  98. logger.info("实盘交易执行完成")
  99. def enable_live_trading(self):
  100. """启用真实交易(谨慎!)"""
  101. confirm = input("⚠️ 即将启用真实交易模式,输入 'YES' 确认: ")
  102. if confirm == "YES":
  103. self.executor.simulation_mode = False
  104. logger.info("已切换到真实交易模式")
  105. else:
  106. logger.info("保持模拟模式")
  107. def main():
  108. """主函数"""
  109. trader = LiveTrader()
  110. print("=" * 60)
  111. print("量化交易系统 - 实盘交易")
  112. print("=" * 60)
  113. print("\n选择操作:")
  114. print("1. 运行每日策略 (模拟模式)")
  115. print("2. 启用真实交易 (⚠️ 危险)")
  116. print("3. 查看账户信息")
  117. print("4. 退出")
  118. choice = input("\n请输入选项 (1-4): ").strip()
  119. if choice == "1":
  120. trader.run_daily()
  121. elif choice == "2":
  122. trader.enable_live_trading()
  123. elif choice == "3":
  124. account = trader.executor.get_account()
  125. print(f"\n总资产: {account['total_asset']:,.0f}元")
  126. print(f"可用资金: {account['available_cash']:,.0f}元")
  127. print(f"持仓市值: {account['market_value']:,.0f}元")
  128. elif choice == "4":
  129. print("退出")
  130. else:
  131. print("无效选项")
  132. if __name__ == "__main__":
  133. main()