You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写可同步多时间帧生成买卖信号的Pine Script脚本?

Pine Script多时间帧同步买卖信号实现

实现逻辑

核心是将你原本运行在10分钟时间帧的策略逻辑封装为公共函数,通过request.security接口拉取所有要求的低时间帧的同策略信号,只有全部时间帧的信号方向一致时才触发最终交易信号,避免单一时间帧信号的假突破问题。

完整可运行代码

//@version=5
strategy("多时间帧同步信号策略", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000, commission_type=strategy.commission.percent, commission_value=0.1)

// ========== 这里替换成你原本10分钟时间帧的策略信号逻辑 ==========
// 示例为简单双均线金叉死叉,直接替换成你的自有策略即可
get_signal() =>
    fast_ma = ta.sma(close, 5)
    slow_ma = ta.sma(close, 20)
    long_signal = ta.crossover(fast_ma, slow_ma)
    short_signal = ta.crossunder(fast_ma, slow_ma)
    [long_signal, short_signal]

// 拉取10分钟基准时间帧的信号
[tf10_long, tf10_short] = request.security(syminfo.tickerid, "10", get_signal())

// 拉取各个低时间帧的同策略信号
[tf1_long, tf1_short] = request.security(syminfo.tickerid, "1", get_signal())
[tf2_long, tf2_short] = request.security(syminfo.tickerid, "2", get_signal())
[tf3_long, tf3_short] = request.security(syminfo.tickerid, "3", get_signal())
[tf5_long, tf5_short] = request.security(syminfo.tickerid, "5", get_signal())

// 所有时间帧信号方向一致才触发最终交易信号
final_long = tf10_long and tf1_long and tf2_long and tf3_long and tf5_long
final_short = tf10_short and tf1_short and tf2_short and tf3_short and tf5_short

// 下单逻辑
if (final_long)
    strategy.entry("多单", strategy.long)
if (final_short)
    strategy.entry("空单", strategy.short)

// 信号可视化标记
plotshape(final_long, title="多信号", location=location.belowbar, color=color.green, style=shape.labelup, text="多", size=size.small)
plotshape(final_short, title="空信号", location=location.abovebar, color=color.red, style=shape.labeldown, text="空", size=size.small)

使用说明

  • 不需要校验的低时间帧可以直接删除对应拉取代码,同时调整final_long/final_short的判断条件即可
  • 回测/实盘运行时,需要把图表时间帧调整为你用到的最低时间帧(此处为1分钟),才能正常拉取所有更高层级时间帧的K线数据
  • 不要开启request.security的barmerge.lookahead_on参数,会引入未来函数导致信号回测失真
  • 部分交易所在2分钟、3分钟时间帧的历史K线数据不足,回测时如果数据缺失可以自行删掉对应时间帧的校验规则

内容的提问来源于stack exchange,提问作者PineDoc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:06:03