pinescript
//@version=5
strategy("MA Direction Engulfing Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// 輸入參數
maLength = input.int(20, "均線長度", minval=1)
stopLossBuffer = input.float(0.1, "止損緩衝區(%)", minval=0.01, step=0.01) / 100
riskRewardRatio = input.float(2.0, "風險收益比", minval=1, step=0.1)
// 計算均線
ma = ta.sma(close, maLength)
maSlope = ma - ma[1] // 均線斜率
// 識別吞沒形態
bullishEngulfing = close[1] < open[1] and // 前一根是陰線
close > open and // 當前是陽線
open <= close[1] and // 開盤價低於或等於前一根收盤價
close >= open[1] // 收盤價高於或等於前一根開盤價
bearishEngulfing = close[1] > open[1] and // 前一根是陽線
close < open and // 當前是陰線
open >= close[1] and // 開盤價高於或等於前一根收盤價
close <= open[1] // 收盤價低於或等於前一根開盤價
// 入場條件
longCondition = maSlope > 0 and close > ma and bullishEngulfing
shortCondition = maSlope < 0 and close < ma and bearishEngulfing
// 止損和止盈計算
var float longStop = na
var float longTarget = na
var float shortStop = na
var float shortTarget = na
// 執行多單
if (longCondition and strategy.position_size == 0)
longStop := low * (1 - stopLossBuffer)
riskAmount = close - longStop
longTarget := close + (riskAmount * riskRewardRatio)
strategy.entry("Long", strategy.long)
// 執行空單
if (shortCondition and strategy.position_size == 0)
shortStop := high * (1 + stopLossBuffer)
riskAmount = shortStop - close
shortTarget := close - (riskAmount * riskRewardRatio)
strategy.entry("Short", strategy.short)
// 設置止損和止盈
if (strategy.position_size > 0)
strategy.exit("Long Exit", "Long", stop=longStop, limit=longTarget)
if (strategy.position_size < 0)
strategy.exit("Short Exit", "Short", stop=shortStop, limit=shortTarget)
// 繪製均線
plot(ma, color=maSlope > 0 ? color.green : color.red, linewidth=2, title="MA")
// 標記吞沒形態
plotshape(bullishEngulfing and not longCondition, style=shape.triangleup, location=location.belowbar,
color=color.new(color.green, 50), size=size.small, title="Bullish Engulfing")
plotshape(bearishEngulfing and not shortCondition, style=shape.triangledown, location=location.abovebar,
color=color.new(color.red, 50), size=size.small, title="Bearish Engulfing")
// 標記入場信號
plotshape(longCondition, style=shape.labelup, location=location.belowbar,
color=color.green, text="BUY", textcolor=color.white, size=size.small)
plotshape(shortCondition, style=shape.labeldown, location=location.abovebar,
color=color.red, text="SELL", textcolor=color.white, size=size.small)
// 繪製止損和止盈水平
plot(strategy.position_size > 0 ? longStop : na, color=color.red, style=plot.style_linebr, linewidth=1, title="Long Stop")
plot(strategy.position_size > 0 ? longTarget : na, color=color.green, style=plot.style_linebr, linewidth=1, title="Long Target")
plot(strategy.position_size < 0 ? shortStop : na, color=color.red, style=plot.style_linebr, linewidth=1, title="Short Stop")
plot(strategy.position_size < 0 ? shortTarget : na, color=color.green, style=plot.style_linebr, linewidth=1, title="Short Target")