3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 ptrade 量化交易平台中,传统的 handle_data 函数主要用于处理分钟级别或日线级别的行情事件。如果策略需要更高的执行频率(如每隔几秒查询一次实时快照或进行打单),可以使用 run_interval 接口。
run_interval 接口说明run_interval 用于以固定的时间间隔(单位为秒)周期性运行指定的自定义函数。
run_interval(context, func, seconds=10)
context 作为唯一参数,例如 def my_func(context):。initialize 函数中进行设置。run_interval 设置不同的定时任务,系统会以多线程形式并行运行。需要注意不同线程之间的变量共享与逻辑冲突。以下示例展示了如何在 initialize 中使用 run_interval 设置一个每 5 秒轮询一次最新行情并触发委托的策略:
def initialize(context):
# 设置标的股票
g.security = '600570.SS'
set_universe(g.security)
# 设置按 5 秒间隔周期性执行 interval_handle 函数
run_interval(context, interval_handle, seconds=5)
def interval_handle(context):
# 获取实时行情快照
snapshot = get_snapshot(g.security)
if not snapshot or g.security not in snapshot:
return
last_price = snapshot[g.security].get('last_px', 0)
log.info("当前%s最新价: %s" % (g.security, last_price))
# 获取当前资金并判断交易逻辑
cash = context.portfolio.cash
if cash > last_price * 100:
# 买入 100 股
order(g.security, 100)
log.info("触发秒级定时任务,下单买入 %s" % g.security)
def handle_data(context, data):
pass
run_interval 任务同时修改全局变量 g 中的数据,需做好逻辑互斥或状态标记,避免产生并发冲突。run_interval 中避免与 handle_data 或 run_daily 同一时刻频繁调用 get_history / get_price 等历史行情接口,防止触发流量限制或造成获取数据为空的问题。