# -*- coding: utf-8 -*- """ 交易执行模块 (模拟股票购买/抛售) """ import time import csv from datetime import datetime from utils_time import now_et, fmt_et class Trader: def __init__(self): self.log_file = "trade_log.csv" self._init_log_file() def _init_log_file(self): try: with open(self.log_file, 'a', newline='', encoding='utf-8-sig') as f: pass # 确保文件存在 except Exception as e: print(f"❌ 初始化交易日志失败: {e}") def execute_signals(self, signals): """ 执行交易信号 Args: signals: 交易信号列表 """ if not signals: return print(f"⚡ 收到 {len(signals)} 个交易信号,准备执行...") for signal in signals: self._execute_single_trade(signal) def _execute_single_trade(self, signal): """执行单笔交易""" action = signal.get('type', '') symbol = signal.get('symbol', '') name = signal.get('name', '') price = signal.get('price', '') reason = signal.get('reason', '') # 模拟交易延迟 time.sleep(0.1) timestamp = fmt_et() log_entry = f"[{timestamp}] {action} {symbol} ({name}) @ ${price} | 原因: {reason}" print(f"💸 交易执行: {log_entry}") # 记录到文件 self._log_trade(timestamp, action, symbol, name, price, reason) def _log_trade(self, timestamp, action, symbol, name, price, reason): try: with open(self.log_file, 'a', newline='', encoding='utf-8-sig') as f: writer = csv.writer(f) writer.writerow([timestamp, action, symbol, name, price, reason]) except Exception as e: print(f"❌ 写入交易日志失败: {e}")