# coding:gbk import datetime account = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 全局变量用于跟踪已触发9%盈利的持仓 triggered_positions = {} def init(ContextInfo): # 设置对应的资金账号 ContextInfo.set_account(account) holdings = ContextInfo.get_holdings() def account_callback(ContextInfo, accountInfo): print(show_data(accountInfo)) def show_data(data): tdata = {} for ar in dir(data): if ar[:2] != 'm_':continue try: tdata[ar] = data.__getattribute__(ar) except: tdata[ar] = '' return tdata def quote_callback(ContextInfo, quote_info): """行情数据更新回调""" current_time = datetime.datetime.now() # 只在交易时间内执行 if current_time.hour >= 9 and current_time.hour < 15: # 从行情信息中提取symbol和当前价格 symbol = quote_info.m_symbol # 假设行情数据包含股票代码 current_price = quote_info.m_last_price # 假设行情数据包含最新价格 # 调用检查函数,传入当前行情价格 check_and_sell_positions_with_price(ContextInfo, symbol, current_price) def check_and_sell_positions_with_price(ContextInfo, symbol, current_price): """带行情价格的持仓检查函数""" holdings = ContextInfo.get_holdings() current_time = datetime.datetime.now() today = current_time.date() # 只处理指定股票 if symbol in holdings: position = holdings[symbol] # 获取持仓的开仓日期 open_date = getattr(position, 'm_open_date', None) # 跳过今日开仓的股票 if open_date and open_date.date() == today: print(f"股票 {symbol} 为今日开仓,跳过监控") return cost_basis = position.m_cost_price quantity = position.m_quantity # 计算当前盈利率 profit_pct = calculate_profit_percentage(current_price, cost_basis) # 如果盈利达到9%,开始监控 if profit_pct >= 9: if symbol not in triggered_positions: # 首次触发9%盈利,记录最高价和时间 triggered_positions[symbol] = { 'new_price': current_price, 'trigger_time': current_time, 'cost_basis': cost_basis, 'quantity': quantity } print(f"股票 {symbol} 盈利达到9%,开始监控,当前价格: {current_price}") else: # 更新最高价 if current_price > triggered_positions[symbol]['new_price']: triggered_positions[symbol]['new_price'] = current_price triggered_positions[symbol]['trigger_time'] = current_time print(f"股票 {symbol} 刷新最高价: {current_price}") # 检查是否需要平仓(从最高点回撤) last_price = triggered_positions[symbol]['new_price'] drawdown_pct = ((last_price - current_price) / last_price) * 100 # 当回撤达到一定比例时平仓(例如0.5%回撤) if drawdown_pct >= 0.5: print(f"股票 {symbol} 从最高点回撤 {drawdown_pct:.2f}%,执行平仓") ContextInfo.place_order(symbol, 'SELL', quantity, current_price) # 移除已平仓的持仓 del triggered_positions[symbol] else: # 如果盈利低于9%,且之前被监控过,则移除监控 if symbol in triggered_positions: print(f"股票 {symbol} 盈利回落至 {profit_pct:.2f}%,取消监控") del triggered_positions[symbol] def calculate_profit_percentage(current_price, cost_basis): return ((current_price - cost_basis) / cost_basis) * 100 def get_current_price(symbol): # 这里需要实现获取实时价格的逻辑 # 可能需要调用QMT的行情接口 pass # 计算持仓盈利率 def calculate_profit_percentage(current_price, cost_basis): return ((current_price - cost_basis) / cost_basis) * 100