3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在实际的量化交易和实盘管理中,许多交易员需要在一套策略代码中兼容多个不同的资金账户,或者针对不同的账户(如大资金账户与小资金账户)执行不同的风控标准和交易逻辑。在 ptrade 平台中,我们可以通过 get_user_name() 接口轻松实现这一需求。
get_user_name()str 类型)或者 None(获取失败时)。initialize 阶段调用 get_user_name() 获取当前运行策略的资金账号。handle_data 或其他交易事件中,根据当前账号的配置执行差异化的下单与风控逻辑。以下源码展示了如何识别两个不同的资金账号(例如 '123456789' 和 '987654321'),并分别为它们配置不同的单笔买入上限,从而实现差异化风控:
def initialize(context):
# 设置操作的股票池
g.security = '600570.SS' # 恒生电子
set_universe(g.security)
# 获取当前登录的资金账号
g.user_name = get_user_name()
log.info("当前登录的资金账号为: %s" % g.user_name)
# 初始化风控参数字典
g.risk_config = {}
# 针对不同的账号设置不同的风控规则
if g.user_name == "123456789":
# 账号A:大资金账户,允许单笔买入 1000 股
g.risk_config['max_buy_amount'] = 1000
g.risk_config['account_type'] = "Large_Capital"
elif g.user_name == "987654321":
# 账号B:小资金账户,单笔买入限制为 100 股
g.risk_config['max_buy_amount'] = 100
g.risk_config['account_type'] = "Small_Capital"
else:
# 默认安全风控配置(如回测环境或未授权账号)
g.risk_config['max_buy_amount'] = 100
g.risk_config['account_type'] = "Default_Safe"
log.info("账户类型: %s, 单笔最大买入量限制: %d" % (g.risk_config['account_type'], g.risk_config['max_buy_amount']))
g.has_ordered = False
def handle_data(context, data):
# 简单示例:仅在未交易时触发一次买入
if not g.has_ordered:
buy_amount = g.risk_config['max_buy_amount']
# 执行差异化风控下的报单
order_id = order(g.security, buy_amount)
if order_id:
log.info("账号 %s 成功发送委托,数量: %d" % (g.user_name, buy_amount))
g.has_ordered = True
else:
log.error("账号 %s 委托失败" % g.user_name)
get_user_name() 可能会返回 None 或默认模拟账号。因此,策略中务必编写 else 分支以提供默认的安全风控参数,避免策略因找不到配置而报错终止。initialize 中对账号及风控变量进行正确的重新初始化,配合 set_parameters(not_restart_trade="1") 等参数可以更好地管理实盘稳定性。