3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在聚宽(JoinQuant)模拟交易中,实时风控是保障资金安全的重要环节。当策略触发止损条件时,通过微信实时接收通知能让交易者第一时间掌握账户动态。本文将详细介绍如何使用聚宽特有的 send_message 函数实现这一功能。
聚宽提供了 send_message 接口,专门用于在官网实时运行的模拟交易中向用户绑定的微信发送自定义消息。
send_message(message, channel='weixin')
'weixin'(默认值)。True 或 False,表示是否发送成功。send_message)每个账号每天最多发送 5 条,超出部分会发送失败(可通过积分兑换更多额度)。以下是一个实用的双均线策略,当个股价格跌破止损线(如买入成本的 95%)时,策略会自动卖出平仓,并调用 send_message 向绑定的微信推送详细的止损信息。
# 导入聚宽函数库
import jqdata
def initialize(context):
# 设定操作的股票:平安银行
g.security = '000001.XSHE'
# 设定沪深300作为基准
set_benchmark('000300.XSHG')
# 开启动态复权模式(真实价格)
set_option('use_real_price', True)
# 设定止损比例(例如:相比持仓均价下跌 5% 则止损)
g.stop_loss_ratio = 0.95
# 每天运行
run_daily(market_open, time='every_bar')
def market_open(context):
security = g.security
current_data = get_current_data()
# 获取当前最新价格
current_price = current_data[security].last_price
# 1. 止损风控逻辑检查
if security in context.portfolio.positions:
position = context.portfolio.positions[security]
# 获取持仓均价
avg_cost = position.avg_cost
# 如果当前价格低于止损价,执行止损平仓
if current_price <= avg_cost * g.stop_loss_ratio:
order_target(security, 0)
log.warning(f"触发止损!股票: {security}, 持仓均价: {avg_cost}, 当前价: {current_price}")
# 构造微信推送消息(注意:控制在200字以内,不含换行符)
msg = f"【实时风控提示】您的模拟盘策略已触发止损!标的:{security},持仓均价:{avg_cost:.2f}元,止损触发价:{current_price:.2f}元,已执行一键清仓。"
# 发送微信通知
send_status = send_message(msg, channel='weixin')
if send_status:
log.info("微信止损通知发送成功!")
else:
log.error("微信止损通知发送失败,请检查绑定状态或日发送配额。")
return
# 2. 常规买入逻辑(示例:价格高于5日均线1%且有现金则买入)
close_data = attribute_history(security, 5, '1d', ['close'])
MA5 = close_data['close'].mean()
cash = context.portfolio.available_cash
if current_price > 1.01 * MA5 and security not in context.portfolio.positions:
if cash > 0:
order_value(security, cash)
log.info(f"Buying {security}")
send_message,常规的每日收盘汇报或下单记录建议依赖系统自带的下单通知。