均线交叉附近日本蜡烛组最小值获取及PineScript实现求助
均线交叉附近K线止损实现方案
核心实现逻辑
- 新增可调整参数配置止损统计的K线数量,支持灵活修改
- 金叉做多时,取交叉触发时点往前N根K线(含交叉当前K线)的最低价作为止损位,相比用收盘价更符合实盘止损逻辑
- 死叉做空时,取对应区间的最高价作为止损位
- 记录止损位对应的K线偏移量,通过绘图函数标记目标K线
关键可用函数说明
lowest(source, length):返回length周期内source序列的最小值,统计多单止损时source传入low即可highest(source, length):返回length周期内source序列的最大值,用于空单止损统计valuewhen(condition, source, bars):返回condition触发第bars次时的source值,可直接提取交叉触发时计算的止损价,无需额外维护全局变量barssince(condition):返回上一次condition触发到当前的K线数,用于定位止损对应的K线位置
完整修改后代码
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Dark_Trader-x01 //@version=4 strategy("SL_around_cross", overlay=true) // 可调整参数 sl_lookback = input(title="止损统计K线数量", type=input.integer, defval=3) // 变量声明 var float sl_buy = na var float sl_sell = na var int sl_buy_bar_offset = na var int sl_sell_bar_offset = na // EMAs计算 EMA_9 = ema(close, 9) EMA_21 = ema(close, 21) EMA_100 = ema(close, 100) // 均线交叉条件 cruce_BUY = crossover(EMA_9, EMA_21) cruce_SELL = crossunder(EMA_9, EMA_21) // 止损计算+对应K线偏移记录 if cruce_BUY // 取当前往前sl_lookback根的最低价最小值 sl_buy := lowest(low, sl_lookback) // 计算最低值对应的K线偏移量 sl_buy_bar_offset := lowestbars(low, sl_lookback) if cruce_SELL sl_sell := highest(high, sl_lookback) sl_sell_bar_offset := highestbars(high, sl_lookback) // 策略执行 strategy.entry("BUY", strategy.long, 2000, when = cruce_BUY) strategy.exit("BUY_EXIT", "BUY", stop=sl_buy, when = cruce_SELL) strategy.entry("SELL", strategy.short, 2000, when = cruce_SELL) strategy.exit("SELL_EXIT", "SELL", stop=sl_sell, when = cruce_BUY) // 绘图标记 // 交叉信号 plotshape(cruce_BUY, style=shape.arrowup, text="多", location=location.belowbar, color=color.green, size=size.small) plotshape(cruce_SELL, style=shape.arrowdown, text="空", location=location.abovebar, color=color.red, size=size.small) // 止损位对应的K线标记 plotshape(cruce_BUY and not na(sl_buy_bar_offset), style=shape.labelup, text="止损K线", location=location.belowbar, color=color.new(color.blue, 0), textcolor=color.white, offset=sl_buy_bar_offset, size=size.tiny) plotshape(cruce_SELL and not na(sl_sell_bar_offset), style=shape.labeldown, text="止损K线", location=location.abovebar, color=color.new(color.orange, 0), textcolor=color.white, offset=sl_sell_bar_offset, size=size.tiny) // 止损线绘制 plot(sl_buy, color=color.green, title="多单止损", linewidth=1, style=plot.style_dashed) plot(sl_sell, color=color.red, title="空单止损", linewidth=1, style=plot.style_dashed)
补充优化点
如果需要包含交叉后N根K线的极值再调整止损,可以结合barssince(cruce_BUY) <= N的条件,在交叉后N根K线走完后再重新计算止损值,适配不同的止损规则。
内容的提问来源于stack exchange,提问作者Dark_Coder
相关产品推荐
相关产品推荐

