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

PineScript v5:如何设置开仓时前5根K线最低价的固定止损?

PineScript 修正:开仓时锁定前5根K线最低价作为固定止损

你的代码中止损价随新K线变化的核心原因是:每次K线更新时,low5和low1会基于当前K线重新计算,而非锁定在开仓时刻的数值。需要在开仓瞬间计算并固定止损价,后续不再修改。

修正后的完整代码

//@version=5
strategy("Strategy Alert", overlay=true, calc_on_every_tick=true, calc_on_order_fills=true, pyramiding = 0)

// --- 补充原代码缺失的指标定义(示例)---
length = 20
src = close
mult = 2.0
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
lower = basis - dev

rsi_length = 14
rsi = ta.rsi(src, rsi_length)

adx_length = 14
adx = ta.adx(adx_length)
plus = ta.plus_di(adx_length)
minus = ta.minus_di(adx_length)
// --- 指标定义结束 ---

//Condition 1 
BBAlert = ta.barssince(ta.crossunder(low[1], lower[1])) <= 10 and close > lower and close > low[1]
//Condition 2 
RSIAlert = ta.barssince(ta.crossunder(rsi,30)) <= 10 and rsi > rsi[1]
//Condition 3 (ADX>-DI>+DI)
DMIAlert = adx[1] > minus[1] and minus[1] > plus[1] and adx[1] > adx and minus[1] > minus and plus[1] < plus and plus < adx
//Condition Sum 
Long = (BBAlert or RSIAlert) and DMIAlert

//Define
varip float stoplosspricel = na  // 用varip保留值,仅在开仓时更新
entryp = strategy.opentrades.entry_price(strategy.opentrades - 1)
conl = entryp <= basis  // 修正原代码笔误:con1改为conl
l1 = ta.lowest(low, 2)

//Set Entry (Long)
if Long
    strategy.entry("long", strategy.long, 1, comment = "buy long")

// 开仓时计算并固定止损价
if strategy.position_size == 1 and strategy.opentrades == 1
    // 计算开仓时刻之前5根K线的最低价(当前开仓K线的前1到前5根)
    stoplosspricel := conl ? ta.lowest(low[1], 5) : l1

// 全局设置止损,使用固定的stoplosspricel
if strategy.position_size > 0 and not na(stoplosspricel)
    strategy.exit("stop loss long", "long", stop = stoplosspricel)

关键修改说明

  • 固定止损价存储:使用varip类型变量stoplosspricel,确保变量值在脚本运行期间持续保留,仅在开仓时更新
  • 开仓时锁定计算:通过strategy.position_size == 1判断刚建立多仓的状态,此时计算开仓K线之前5根的最低价(ta.lowest(low[1], 5)),避免后续K线更新时重新计算
  • 修正笔误:原代码中con1应为conl,已同步修正
  • 独立止损指令:将strategy.exit移出开仓条件块,放在全局作用域,确保止损指令始终生效,且使用固定的止损价

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:05:38