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

Pine Script策略修改:实现连续2根K线收盘价触发平仓条件

修改Pine Script策略:连续2根K线满足条件触发平仓

原策略在单根K线收盘价满足平仓条件时立即平仓,现调整为连续2根K线收盘价均达到对应平仓条件才执行平仓操作,核心思路是通过Pine Script的历史数据引用语法[1]检查上一根K线是否也满足相同条件。

修改后的完整代码

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bubblyApple52984

//@version=5
strategy("EMA strategy", overlay=true, process_orders_on_close = true, margin_long=100, margin_short=100)
ema_input1 = input.int(1, "Fast")
ema_input2 = input.int(2, "Slow")
sma_input3 = input.int(3, "SuperSlow")

plot(ta.ema(close, ema_input1),"fast",color.green)
plot (ta.ema(close, ema_input2),"slow",color.white)
plot (ta.sma(close, sma_input3), "superslow",color.red)

shortCondition1 = close < ta.sma(close, sma_input3)
shortCondition2 = ta.crossunder(ta.ema(close, ema_input1), ta.ema(close, ema_input2))
shortCondition3 = ta.ema(close,ema_input1) < ta.sma(close, sma_input3)
shortCondition4 = ta.ema(close,ema_input2) < ta.sma(close, sma_input3)
exitConditionShort1 = close >= ta.ema(close, ema_input2)
//exitConditionShort2 = ta.crossover(ta.ema(close, ema_input1), ta.ema(close, ema_input2))
inTradeShort = strategy.position_size < 0
if (shortCondition1 and shortCondition2 and  shortCondition3 and shortCondition4)
    strategy.entry("My Short Entry Id", strategy.short)
// 新增检查上一根K线是否也满足平仓条件
if (exitConditionShort1 and exitConditionShort1[1] and inTradeShort)
    strategy.close(id="My Short Entry Id", comment="CloseShort")
    
longCondition1 = close > ta.sma(close, sma_input3)
longCondition2 = ta.crossover(ta.ema(close, ema_input1), ta.ema(close, ema_input2))
longCondition3 = ta.ema(close,ema_input1) > ta.sma(close, sma_input3)
longCondition4 = ta.ema(close,ema_input2) > ta.sma(close, sma_input3)
exitConditionlong1 = close <= ta.ema(close, ema_input2)
//exitConditionlong2 = ta.crossunder(ta.ema(close, ema_input1), ta.ema(close, ema_input2))
inTradelong = strategy.position_size > 0
if (longCondition1 and longCondition2 and longCondition3 and longCondition4)
    strategy.entry("My Long Entry Id", strategy.long)
// 新增检查上一根K线是否也满足平仓条件
if (exitConditionlong1 and exitConditionlong1[1] and inTradelong)
    strategy.close(id="My Long Entry Id", comment="CloseLong")

关键修改说明

  • 空头平仓逻辑:将原平仓条件exitConditionShort1扩展为当前K线+上一根K线均满足条件,即exitConditionShort1 and exitConditionShort1[1],[1]代表引用上一根K线的条件结果。
  • 多头平仓逻辑:同理,将原平仓条件exitConditionlong1扩展为exitConditionlong1 and exitConditionlong1[1],确保连续两根K线符合要求才触发平仓。

内容的提问来源于stack exchange,提问作者Sam.S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:05:18