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

如何在Pine Script中实现带±2阈值的Slow Stoch金叉/死叉策略?

在Pine Script中实现带差值阈值的慢速随机指标交叉策略

要实现你需要的「交叉时k与d差值达到±2」的逻辑,只需在原有交叉判断条件中额外加入差值阈值校验即可。以下是修改后的完整代码及关键改动说明:

修改后的完整代码

//Stochastic Inputs
length = input.int(14, minval=1)
OverBought = input(80)
OverSold = input(20)
smoothK = 3
smoothD = 3
// 新增差值阈值输入(可灵活调整)
diffThreshold = input.int(2, minval=1, title="交叉差值阈值")

k = ta.sma(ta.stoch(close, high, low, length), smoothK)
d = ta.sma(k, smoothD)

//Rule to define crossover /crossunder
co = ta.crossover(k,d)
cu = ta.crossunder(k,d)

if (not na(k) and not na(d))
    // 做多条件:k上穿d + 差值≥阈值 + k在超卖区 + 处于上升趋势
    if (co and k < OverSold and is_uptrend and (k - d) >= diffThreshold)
        strategy.entry("Long", strategy.long, comment="Long")
    // 做空条件:k下穿d + 差值≤-阈值 + k在超买区 + 处于下降趋势
    if (cu and k > OverBought and is_downtrend and (k - d) <= -diffThreshold)
        strategy.entry("Short", strategy.short, comment="Short")

关键改动说明

  • 新增差值阈值参数:把固定的±2做成可输入参数diffThreshold,方便后续灵活调整阈值大小。
  • 强化交叉条件:
    • 上穿做多时,要求交叉完成后k - d的差值≥设定阈值(默认2),确保k线确实大幅上穿d线
    • 下穿做空时,要求交叉完成后k - d的差值≤-设定阈值(默认-2),确保k线确实大幅下穿d线
  • 修正订单命名错误:原代码中做空订单的strategy.entry名称和comment都写成了"Long",已改为"Short",避免订单标识混乱

注意:代码中用到的is_uptrend和is_downtrend变量,需要确保你已在脚本其他部分完成定义(比如通过均线或其他趋势判断逻辑实现),否则会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:40:29