以下是根据您提供的逻辑,使用 Pine Script 编写的策略代码。这个策略基于 20 周期简单移动平均线 (SMA) 的方向和吞没K线模式(engulfing pattern)。策略逻辑如下:
pinescript
//@version=5
strategy("SMA Engulfing Trend Strategy", overlay=true, process_orders_on_close=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// 输入参数
sma_length = input.int(20, title="SMA Length", minval=1) // SMA周期,默认为20
sl_offset = input.float(0.0005, title="SL Offset", tooltip="Stop Loss Offset in price units, e.g., 0.0005 for XAUUSD") // 止损偏移量,默认为0.0005
// 计算SMA
sma_value = ta.sma(close, sma_length)
// 计算SMA斜率(使用变化量判断斜率方向)
sma_slope_up = ta.change(sma_value) > 0 ? 1 : 0 // SMA斜率向上(>0)
sma_slope_down = ta.change(sma_value) < 0 ? 1 : 0 // SMA斜率向下(<0)
// 检测吞没K线模式
bullish_engulfing = close[1] < open[1] and close > open and open <= close[1] and close >= open[1] // 看涨吞没:前一根阴线,当前阳线,且当前实体吞没前一根实体
bearish_engulfing = close[1] > open[1] and close < open and open >= close[1] and close <= open[1] // 看跌吞没:前一根阳线,当前阴线,且当前实体吞没前一根实体
// 入场条件
long_condition = sma_slope_up and close > sma_value and bullish_engulfing // 做多条件:SMA向上、价格在SMA上方、看涨吞没
short_condition = sma_slope_down and close < sma_value and bearish_engulfing // 做空条件:SMA向下、价格在SMA下方、看跌吞没
// 入场和设置止损/止盈
if long_condition
strategy.entry("Long Entry", strategy.long) // 做多入场
sl_long = low - sl_offset // 止损价格:入场K线低点下方偏移
risk_long = close - sl_long // 风险距离:入场价到止损价的距离
tp_long = close + 2 * risk_long // 止盈价格:入场价 + 2倍风险
strategy.exit("Exit Long", from_entry="Long Entry", stop=sl_long, limit=tp_long) // 设置止损和止盈
if short_condition
strategy.entry("Short Entry", strategy.short) // 做空入场
sl_short = high + sl_offset // 止损价格:入场K线高点上方偏移
risk_short = sl_short - close // 风险距离:止损价到入场价的距离(做空时止损在上面)
tp_short = close - 2 * risk_short // 止盈价格:入场价 - 2倍风险
strategy.exit("Exit Short", from_entry="Short Entry", stop=sl_short, limit=tp_short) // 设置止损和止盈
// 绘图:显示SMA以便可视化
plot(sma_value, color=color.blue, title="SMA", linewidth=2)
// 可选:标记入场信号(用于可视化)
plotshape(long_condition and strategy.position_size == 0, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="Long Signal")
plotshape(short_condition and strategy.position_size == 0, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, title="Short Signal")