本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script(R) code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) IndicatorEliteFlow
//@version=6
indicator("Engulfing Context Score [IEF]", shorttitle="ECS [IEF]", overlay=true, max_labels_count=500)
// Engulfing Context Score does not stack unrelated indicator confirmations.
// It evaluates how convincingly the current candle rejects and displaces the previous candle,
// then places that event in participation, volatility, and confirmed higher-timeframe context.
string G_PATTERN = "Pattern Definition"
string G_SCORE = "Quality Score"
string G_CONTEXT = "Market Context"
string G_DISPLAY = "Display"
float minBodyAtr = input.float(0.10, "Minimum previous body / ATR", minval=0.0, step=0.05, group=G_PATTERN)
float minBodyRatio = input.float(1.20, "Minimum current / previous body ratio", minval=1.0, step=0.05, group=G_PATTERN)
bool requireFullBody = input.bool(true, "Require full body engulfment", group=G_PATTERN,
tooltip="When disabled, candidates are opposite-color reversal candles and may not engulf the previous body.")
bool requireCloseBreak = input.bool(true, "Require close beyond previous high/low", group=G_PATTERN,
tooltip="Adds displacement: bullish candles must close above the previous high; bearish candles below the previous low.")
int minScore = input.int(65, "Minimum quality score", minval=0, maxval=100, group=G_SCORE)
int cooldownBars = input.int(3, "Signal cooldown bars", minval=0, maxval=100, group=G_SCORE)
float wExpansion = input.float(25, "Weight: body expansion", minval=0, maxval=100, group=G_SCORE)
float wCloseLocation = input.float(20, "Weight: close location", minval=0, maxval=100, group=G_SCORE)
float wRejection = input.float(15, "Weight: rejection wick", minval=0, maxval=100, group=G_SCORE)
float wParticipation = input.float(15, "Weight: relative volume", minval=0, maxval=100, group=G_SCORE)
float wVolatility = input.float(10, "Weight: volatility context", minval=0, maxval=100, group=G_SCORE)
float wRegime = input.float(15, "Weight: confirmed HTF regime", minval=0, maxval=100, group=G_SCORE)
int atrLength = input.int(14, "ATR length", minval=2, group=G_CONTEXT)
int volumeLength = input.int(30, "Relative-volume length", minval=2, group=G_CONTEXT)
int volatilityLength = input.int(50, "ATR baseline length", minval=5, group=G_CONTEXT)
string regimeTf = input.timeframe("60", "Higher-timeframe regime", group=G_CONTEXT)
int regimeFast = input.int(20, "HTF fast EMA", minval=1, group=G_CONTEXT)
int regimeSlow = input.int(50, "HTF slow EMA", minval=2, group=G_CONTEXT)
bool showRaw = input.bool(false, "Show confirmed candidates below threshold", group=G_DISPLAY)
bool showScoreLabels = input.bool(true, "Show score labels", group=G_DISPLAY)
bool colorSignalBars = input.bool(false, "Color qualifying candles", group=G_DISPLAY)
bool showDashboard = input.bool(true, "Show compact dashboard", group=G_DISPLAY)
color bullColor = input.color(color.rgb(20, 184, 116), "Bullish color", group=G_DISPLAY)
color bearColor = input.color(color.rgb(239, 83, 80), "Bearish color", group=G_DISPLAY)
clamp01(float value) => math.min(math.max(value, 0.0), 1.0)
float configuredWeight = wExpansion + wCloseLocation + wRejection + wParticipation + wVolatility + wRegime
if timeframe.in_seconds(regimeTf) < timeframe.in_seconds()
runtime.error("Context timeframe must be equal to or higher than the chart timeframe. Increase the context timeframe in settings.")
if configuredWeight <= 0
runtime.error("At least one score weight must be greater than zero.")
float atr = ta.atr(atrLength)
float prevBody = math.abs(close[1] - open[1])
float currBody = math.abs(close - open)
float candleRange = math.max(high - low, syminfo.mintick)
bool prevBear = close[1] < open[1]
bool prevBull = close[1] > open[1]
bool currBull = close > open
bool currBear = close < open
bool bullEngulf = open <= close[1] and close >= open[1]
bool bearEngulf = open >= close[1] and close <= open[1]
bool bodySizeOk = prevBody >= atr[1] * minBodyAtr and currBody >= prevBody * minBodyRatio
bool bullRaw = prevBear and currBull and bodySizeOk and (not requireFullBody or bullEngulf) and
(not requireCloseBreak or close > high[1])
bool bearRaw = prevBull and currBear and bodySizeOk and (not requireFullBody or bearEngulf) and
(not requireCloseBreak or close < low[1])
// Each component is normalized to 0..1 before weights are applied.
float expansionScore = math.min(math.max(currBody / math.max(prevBody, syminfo.mintick) - 1.0, 0.0), 1.0)
float bullCloseScore = clamp01((close - low) / candleRange)
float bearCloseScore = clamp01((high - close) / candleRange)
float lowerWick = math.min(open, close) - low
float upperWick = high - math.max(open, close)
float bullRejectScore = clamp01(lowerWick / candleRange * 2.0)
float bearRejectScore = clamp01(upperWick / candleRange * 2.0)
float avgVolume = ta.sma(volume, volumeLength)
bool volumeAvailable = not na(volume) and not na(avgVolume) and avgVolume > 0
float relativeVolume = volumeAvailable ? volume / avgVolume : na
float participationScore = volumeAvailable ? clamp01((relativeVolume - 0.75) / 1.25) : 0.5
float atrBaseline = ta.sma(atr, volatilityLength)
float relativeAtr = na(atrBaseline) or atrBaseline == 0 ? 1.0 : atr / atrBaseline
// Reward an active but not extremely stretched regime.
float volatilityScore = relativeAtr <= 1.5 ? clamp01((relativeAtr - 0.60) / 0.90) :
clamp01(1.0 - (relativeAtr - 1.5) / 1.5)
// [1] is evaluated inside request.security so only the last completed HTF bar is used.
float htfFast = request.security(syminfo.tickerid, regimeTf, ta.ema(close, regimeFast)[1], lookahead=barmerge.lookahead_on)
float htfSlow = request.security(syminfo.tickerid, regimeTf, ta.ema(close, regimeSlow)[1], lookahead=barmerge.lookahead_on)
float bullRegimeScore = htfFast > htfSlow ? 1.0 : 0.0
float bearRegimeScore = htfFast < htfSlow ? 1.0 : 0.0
float totalWeight = configuredWeight > 0 ? configuredWeight : 1.0
float bullScoreRaw = (expansionScore * wExpansion + bullCloseScore * wCloseLocation + bullRejectScore * wRejection +
participationScore * wParticipation + volatilityScore * wVolatility + bullRegimeScore * wRegime) / totalWeight * 100.0
float bearScoreRaw = (expansionScore * wExpansion + bearCloseScore * wCloseLocation + bearRejectScore * wRejection +
participationScore * wParticipation + volatilityScore * wVolatility + bearRegimeScore * wRegime) / totalWeight * 100.0
int bullScore = int(math.round(bullScoreRaw))
int bearScore = int(math.round(bearScoreRaw))
var int lastSignalBar = na
bool cooldownOk = na(lastSignalBar) or bar_index - lastSignalBar > cooldownBars
bool bullSignal = barstate.isconfirmed and bullRaw and bullScore >= minScore and cooldownOk
bool bearSignal = barstate.isconfirmed and bearRaw and bearScore >= minScore and cooldownOk
if bullSignal or bearSignal
lastSignalBar := bar_index
plotshape(bullSignal and not showScoreLabels, "Qualified bullish engulfing", shape.triangleup, location.belowbar, bullColor, size=size.small)
plotshape(bearSignal and not showScoreLabels, "Qualified bearish engulfing", shape.triangledown, location.abovebar, bearColor, size=size.small)
plotshape(showRaw and barstate.isconfirmed and bullRaw and bullScore < minScore, "Below-threshold bullish candidate", shape.circle, location.belowbar, color.new(bullColor, 70), size=size.tiny)
plotshape(showRaw and barstate.isconfirmed and bearRaw and bearScore < minScore, "Below-threshold bearish candidate", shape.circle, location.abovebar, color.new(bearColor, 70), size=size.tiny)
if bullSignal and showScoreLabels
label.new(bar_index, low, "B " + str.tostring(bullScore), yloc=yloc.belowbar, style=label.style_label_up, color=bullColor, textcolor=color.white, size=size.tiny)
if bearSignal and showScoreLabels
label.new(bar_index, high, "S " + str.tostring(bearScore), yloc=yloc.abovebar, style=label.style_label_down, color=bearColor, textcolor=color.white, size=size.tiny)
barcolor(colorSignalBars ? (bullSignal ? bullColor : bearSignal ? bearColor : na) : na)
var table dashboard = table.new(position.top_right, 2, 4, border_width=1)
if barstate.islast and showDashboard
string stateText = (barstate.isconfirmed ? "" : "Live: ") + (bullRaw ? "Bull " + str.tostring(bullScore) : bearRaw ? "Bear " + str.tostring(bearScore) : "No pattern")
color stateColor = bullRaw ? bullColor : bearRaw ? bearColor : color.gray
table.cell(dashboard, 0, 0, "ECS", text_color=color.white, bgcolor=color.rgb(35, 39, 47))
table.cell(dashboard, 1, 0, stateText, text_color=color.white, bgcolor=stateColor)
table.cell(dashboard, 0, 1, "Rel volume", text_color=color.silver)
table.cell(dashboard, 1, 1, volumeAvailable ? str.tostring(relativeVolume, "#.00") + "x" : "N/A (neutral)", text_color=color.white)
table.cell(dashboard, 0, 2, "ATR regime", text_color=color.silver)
table.cell(dashboard, 1, 2, str.tostring(relativeAtr, "#.00") + "x", text_color=color.white)
table.cell(dashboard, 0, 3, "HTF regime", text_color=color.silver)
table.cell(dashboard, 1, 3, htfFast > htfSlow ? "Bullish" : htfFast < htfSlow ? "Bearish" : "Neutral", text_color=color.white)
if barstate.islast and not showDashboard
table.clear(dashboard, 0, 0, 1, 3)
alertcondition(bullSignal, "Qualified Bullish Engulfing", "Bullish engulfing context score qualified on {{ticker}} {{interval}} at {{close}}")
alertcondition(bearSignal, "Qualified Bearish Engulfing", "Bearish engulfing context score qualified on {{ticker}} {{interval}} at {{close}}")