Base Candles, Engulfing

Saleh_ABO_RAED · study · 565 行 · 点赞 17 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Saleh_ABO_RAED
 
//@version=6
indicator("Base Candles, Engulfing", overlay=true)
 
//═════════════════════════════════════════════════════════════════════════════
// 1. USER SETTINGS
//═════════════════════════════════════════════════════════════════════════════
 
// Base candle settings
dojiBodyPercent = input.float(
     15.0,
     "Maximum Base Body Size (%)",
     minval=5.0,
     maxval=100.0,
     group="Base Candle Settings",
     tooltip="Maximum candle body size as a percentage of the candle's full high-low range.")
 
baseColor = input.color(
     color.white,
     "Base Marker Color",
     group="Base Candle Settings")
 
// Engulfing settings
strictMode = input.bool(
     false,
     "Strict Engulfing Mode (Full Body Coverage)",
     group="Engulfing Settings",
     tooltip="Strict mode requires the current candle body to fully cover the previous candle body. Flexible mode allows the open to fall within the previous body by the specified tolerance.")
 
allowOpenInside = input.bool(
     true,
     "Allow Open Inside Previous Candle Body",
     group="Engulfing Settings",
     tooltip="Applies to flexible mode only.")
 
openTolerancePercent = input.float(
     10.0,
     "Maximum Open Penetration (%)",
     minval=0.0,
     maxval=100.0,
     step=0.5,
     group="Engulfing Settings",
     tooltip="The allowed penetration is calculated as a percentage of the previous candle body size.")
 
allowSameDirection = input.bool(
     false,
     "Allow Same-Direction Candles",
     group="Engulfing Settings",
     tooltip="When disabled, a bullish engulfing candle must follow a bearish candle, and a bearish engulfing candle must follow a bullish candle.")
 
confirmEngulfingOnClose = input.bool(
     true,
     "Confirm Engulfing at Bar Close",
     group="Engulfing Settings",
     tooltip="When disabled, the current candle's engulfing color may change before it closes. Engulfing reference levels are always saved only after bar close.")
 
showBullish = input.bool(
     true,
     "Show Bullish Engulfing",
     group="Engulfing Settings",
     tooltip="Visual setting only. Hiding bullish engulfing candles does not prevent their detection or use as breakout references.")
 
bullishColor = input.color(
     color.green,
     "Bullish Engulfing Color",
     group="Engulfing Settings")
 
showBearish = input.bool(
     true,
     "Show Bearish Engulfing",
     group="Engulfing Settings",
     tooltip="Visual setting only. Hiding bearish engulfing candles does not prevent their detection or use as breakdown references.")
 
bearishColor = input.color(
     color.red,
     "Bearish Engulfing Color",
     group="Engulfing Settings")
 
// Breakout and breakdown settings
alertBullishBreak = input.bool(
     true,
     "Enable Bullish Breakout Signals and Alert Condition",
     group="Breakout and Breakdown Settings")
 
alertBearishBreak = input.bool(
     true,
     "Enable Bearish Breakdown Signals and Alert Condition",
     group="Breakout and Breakdown Settings")
 
breakReferenceMode = input.string(
     "Latest Engulfing Candle (Either Direction)",
     "Breakout and Breakdown Reference",
     options=[
         "Latest Engulfing Candle (Either Direction)",
         "By Direction: Bullish High / Bearish Low"
     ],
     group="Breakout and Breakdown Settings",
     tooltip="Latest engulfing: use the high and low of the most recent engulfing candle, regardless of direction. By direction: use the high of the latest bullish engulfing candle and the low of the latest bearish engulfing candle.")
 
confirmBreakOnClose = input.bool(
     true,
     "Confirm Breakout / Breakdown at Bar Close",
     group="Breakout and Breakdown Settings",
     tooltip="When disabled, signals use the current price and may appear or disappear before the bar closes.")
 
requireFreshCross = input.bool(
     true,
     "Require a Fresh Level Cross",
     group="Breakout and Breakdown Settings",
     tooltip="For a breakout, the current price must be above the reference high and the previous close at or below it. For a breakdown, the current price must be below the reference low and the previous close at or above it.")
 
showBreakReferences = input.bool(
     false,
     "Show Latest Reference Levels",
     group="Breakout and Breakdown Settings",
     tooltip="Displays two short reference lines beside the latest bar, without historical reference lines. After a new engulfing candle closes, its saved levels become the references for subsequent bars.")
 
// Liquidity sweep settings
showSweep = input.bool(
     false,
     "Show Liquidity Sweep Signals",
     group="Liquidity Sweep Settings",
     tooltip="Visual setting only. Hiding the arrows does not disable liquidity sweep alert conditions.")
 
sweepBullColor = input.color(
     color.blue,
     "Bullish Sweep Arrow Color",
     group="Liquidity Sweep Settings")
 
sweepBearColor = input.color(
     color.orange,
     "Bearish Sweep Arrow Color",
     group="Liquidity Sweep Settings")
 
sweepCloseMode = input.string(
     "Beyond Previous Candle Body",
     "Sweep Closing Requirement",
     options=[
         "Beyond Previous Candle Body",
         "Back Across Swept Level"
     ],
     group="Liquidity Sweep Settings",
     tooltip="Beyond body: a bullish sweep closes above the previous body, and a bearish sweep below it. Back across level: a bullish sweep closes above the previous low, and a bearish sweep below the previous high.")
 
sweepWickOnly = input.bool(
     true,
     "Require Wick-Only Level Breach",
     group="Liquidity Sweep Settings",
     tooltip="For a bullish sweep, the open must be at or above the previous low. For a bearish sweep, the open must be at or below the previous high. Combined with the closing conditions, this keeps the body on the reclaimed side of the level.")
 
confirmSweepOnClose = input.bool(
     true,
     "Confirm Liquidity Sweep at Bar Close",
     group="Liquidity Sweep Settings")
 
// Moving average settings
show_mas = input.bool(
     true,
     "Show All Moving Averages",
     group="Moving Averages")
 
ma1_type = input.string(
     "SMA",
     "MA 1 Type",
     options=["SMA", "EMA", "WMA", "DEMA", "TEMA", "HMA", "VWMA"],
     group="Moving Averages")
 
ma1_length = input.int(
     8,
     "MA 1 Length",
     minval=1,
     group="Moving Averages")
 
ma1_color = input.color(
     color.rgb(34, 189, 28),
     "MA 1 Color",
     group="Moving Averages")
 
ma2_type = input.string(
     "EMA",
     "MA 2 Type",
     options=["SMA", "EMA", "WMA", "DEMA", "TEMA", "HMA", "VWMA"],
     group="Moving Averages")
 
ma2_length = input.int(
     20,
     "MA 2 Length",
     minval=1,
     group="Moving Averages")
 
ma2_color = input.color(
     color.rgb(236, 35, 35),
     "MA 2 Color",
     group="Moving Averages")
 
ma3_type = input.string(
     "HMA",
     "MA 3 Type",
     options=["SMA", "EMA", "WMA", "DEMA", "TEMA", "HMA", "VWMA"],
     group="Moving Averages")
 
ma3_length = input.int(
     50,
     "MA 3 Length",
     minval=1,
     group="Moving Averages")
 
ma3_color = input.color(
     color.orange,
     "MA 3 Color",
     group="Moving Averages")
 
//═════════════════════════════════════════════════════════════════════════════
// 2. CANDLE PROPERTIES
//═════════════════════════════════════════════════════════════════════════════
 
bodySize = math.abs(close - open)
totalRange = high - low
 
isDoji = totalRange > 0 and bodySize <= totalRange * dojiBodyPercent / 100.0
midCandleBody = (open + close) / 2.0
drawPoint = isDoji ? midCandleBody : na
 
hasPreviousBar = not na(open[1]) and not na(close[1])
 
prevBodyMax = math.max(open[1], close[1])
prevBodyMin = math.min(open[1], close[1])
prevBodySize = prevBodyMax - prevBodyMin
 
bullishCandle = close > open
bearishCandle = close < open
 
prevBullishCandle = close[1] > open[1]
prevBearishCandle = close[1] < open[1]
 
//═════════════════════════════════════════════════════════════════════════════
// 3. ENGULFING CONDITIONS — INDEPENDENT OF DISPLAY SETTINGS
//═════════════════════════════════════════════════════════════════════════════
 
bullishDirectionOK = allowSameDirection or prevBearishCandle
bearishDirectionOK = allowSameDirection or prevBullishCandle
 
useTolerance = allowOpenInside and not strictMode
tolerance = useTolerance ? prevBodySize * openTolerancePercent / 100.0 : 0.0
 
// Strict mode: the current body fully covers the previous body
strictBullish = hasPreviousBar and bullishCandle and bullishDirectionOK and open <= prevBodyMin and close >= prevBodyMax and bodySize > prevBodySize
 
strictBearish = hasPreviousBar and bearishCandle and bearishDirectionOK and open >= prevBodyMax and close <= prevBodyMin and bodySize > prevBodySize
 
// Flexible mode: the open may penetrate the previous body by the allowed amount
relaxedBullish = hasPreviousBar and bullishCandle and bullishDirectionOK and open <= prevBodyMin + tolerance and close > prevBodyMax and bodySize > prevBodySize
 
relaxedBearish = hasPreviousBar and bearishCandle and bearishDirectionOK and open >= prevBodyMax - tolerance and close < prevBodyMin and bodySize > prevBodySize
 
// Pattern detection is independent of visual settings
bullishEngulfingPattern = strictMode ? strictBullish : relaxedBullish
bearishEngulfingPattern = strictMode ? strictBearish : relaxedBearish
 
// Engulfing confirmation for display
engulfingConfirmationOK = not confirmEngulfingOnClose or barstate.isconfirmed
 
engulfingBullish = engulfingConfirmationOK and bullishEngulfingPattern
engulfingBearish = engulfingConfirmationOK and bearishEngulfingPattern
 
// Display conditions only
displayBullishEngulfing = showBullish and engulfingBullish
displayBearishEngulfing = showBearish and engulfingBearish
 
//═════════════════════════════════════════════════════════════════════════════
// 4. LIQUIDITY SWEEPS — PREVIOUS BAR HIGH / LOW
//═════════════════════════════════════════════════════════════════════════════
 
sweepConfirmationOK = not confirmSweepOnClose or barstate.isconfirmed
 
bullishSweepCloseOK = sweepCloseMode == "Beyond Previous Candle Body" ? close > prevBodyMax : close > low[1]
bearishSweepCloseOK = sweepCloseMode == "Beyond Previous Candle Body" ? close < prevBodyMin : close < high[1]
 
// Together with candle direction and closing conditions,
// these checks keep the body on the reclaimed side of the swept level
bullishSweepWickOK = not sweepWickOnly or open >= low[1]
bearishSweepWickOK = not sweepWickOnly or open <= high[1]
 
// Sweep calculations are independent of arrow visibility
bullishSweep = hasPreviousBar and sweepConfirmationOK and bullishCandle and low < low[1] and bullishSweepCloseOK and bullishSweepWickOK
 
bearishSweep = hasPreviousBar and sweepConfirmationOK and bearishCandle and high > high[1] and bearishSweepCloseOK and bearishSweepWickOK
 
//═════════════════════════════════════════════════════════════════════════════
// 5. ENGULFING REFERENCES AND BREAKOUT / BREAKDOWN DETECTION
//═════════════════════════════════════════════════════════════════════════════
 
// Latest bullish engulfing candle
var float lastBullishHigh = na
var int lastBullishBar = na
var bool bullishBreakTriggered = false
 
// Latest bearish engulfing candle
var float lastBearishLow = na
var int lastBearishBar = na
var bool bearishBreakTriggered = false
 
// Latest engulfing candle, regardless of direction
var float lastEngulfingHigh = na
var float lastEngulfingLow = na
var int lastEngulfingBar = na
var bool lastEngulfingHighBroken = false
var bool lastEngulfingLowBroken = false
 
useLatestEngulfing = breakReferenceMode == "Latest Engulfing Candle (Either Direction)"
 
// Capture the previous reference before updating it with the current bar
referenceHigh = useLatestEngulfing ? lastEngulfingHigh : lastBullishHigh
referenceLow = useLatestEngulfing ? lastEngulfingLow : lastBearishLow
 
referenceHighBar = useLatestEngulfing ? lastEngulfingBar : lastBullishBar
referenceLowBar = useLatestEngulfing ? lastEngulfingBar : lastBearishBar
 
highAlreadyBroken = useLatestEngulfing ? lastEngulfingHighBroken : bullishBreakTriggered
lowAlreadyBroken = useLatestEngulfing ? lastEngulfingLowBroken : bearishBreakTriggered
 
// The reference candle must precede the current bar
validHighReference = not na(referenceHigh) and not na(referenceHighBar) and bar_index > referenceHighBar
validLowReference = not na(referenceLow) and not na(referenceLowBar) and bar_index > referenceLowBar
 
breakConfirmationOK = not confirmBreakOnClose or barstate.isconfirmed
 
freshBullishCross = not requireFreshCross or close[1] <= referenceHigh
freshBearishCross = not requireFreshCross or close[1] >= referenceLow
 
// One signal per side of each reference
bullishBreakout = alertBullishBreak and breakConfirmationOK and validHighReference and not highAlreadyBroken and close > referenceHigh and freshBullishCross
 
bearishBreakout = alertBearishBreak and breakConfirmationOK and validLowReference and not lowAlreadyBroken and close < referenceLow and freshBearishCross
 
// Record the break of the previous reference first
if bullishBreakout
    if useLatestEngulfing
        lastEngulfingHighBroken := true
    else
        bullishBreakTriggered := true
 
if bearishBreakout
    if useLatestEngulfing
        lastEngulfingLowBroken := true
    else
        bearishBreakTriggered := true
 
// Update references after checking the current bar.
// Only confirmed engulfing candles can become references.
// Candle color visibility does not affect reference updates.
if barstate.isconfirmed
    if bullishEngulfingPattern
        lastBullishHigh := high
        lastBullishBar := bar_index
        bullishBreakTriggered := false
 
    if bearishEngulfingPattern
        lastBearishLow := low
        lastBearishBar := bar_index
        bearishBreakTriggered := false
 
    if bullishEngulfingPattern or bearishEngulfingPattern
        lastEngulfingHigh := high
        lastEngulfingLow := low
        lastEngulfingBar := bar_index
        lastEngulfingHighBroken := false
        lastEngulfingLowBroken := false
 
//═════════════════════════════════════════════════════════════════════════════
// 6. MOVING AVERAGES
//═════════════════════════════════════════════════════════════════════════════
 
ma(maType, src, len) =>
    switch maType
        "SMA" => ta.sma(src, len)
        "EMA" => ta.ema(src, len)
        "WMA" => ta.wma(src, len)
        "DEMA" =>
            e1 = ta.ema(src, len)
            e2 = ta.ema(e1, len)
            2.0 * e1 - e2
        "TEMA" =>
            e1 = ta.ema(src, len)
            e2 = ta.ema(e1, len)
            e3 = ta.ema(e2, len)
            3.0 * e1 - 3.0 * e2 + e3
        "HMA" => ta.hma(src, len)
        "VWMA" => ta.vwma(src, len)
        => ta.sma(src, len)
 
ma1 = ma(ma1_type, close, ma1_length)
ma2 = ma(ma2_type, close, ma2_length)
ma3 = ma(ma3_type, close, ma3_length)
 
//═════════════════════════════════════════════════════════════════════════════
// 7. VISUAL DISPLAY
//═════════════════════════════════════════════════════════════════════════════
 
// Base candle marker
plotchar(
     drawPoint,
     title="Base Candle",
     char="⁕",
     color=baseColor,
     location=location.absolute,
     size=size.tiny)
 
// Engulfing candle colors
barcolor(
     displayBullishEngulfing ? bullishColor :
     displayBearishEngulfing ? bearishColor : na,
     title="Engulfing Candle Colors")
 
// Engulfing candle level marks
plot(
     displayBullishEngulfing ? high : na,
     title="Bullish Engulfing High",
     color=color.new(bullishColor, 50),
     linewidth=2,
     style=plot.style_linebr)
 
plot(
     displayBearishEngulfing ? low : na,
     title="Bearish Engulfing Low",
     color=color.new(bearishColor, 50),
     linewidth=2,
     style=plot.style_linebr)
 
// Only two short reference lines beside the latest bar
var line currentHighLine = na
var line currentLowLine = na
 
if barstate.islast
    if showBreakReferences
        // Use the saved references after the latest update
        currentReferenceHigh = useLatestEngulfing ? lastEngulfingHigh : lastBullishHigh
        currentReferenceLow = useLatestEngulfing ? lastEngulfingLow : lastBearishLow
 
        // Reference high
        if not na(currentReferenceHigh)
            if na(currentHighLine)
                currentHighLine := line.new(
                     x1=bar_index,
                     y1=currentReferenceHigh,
                     x2=bar_index + 3,
                     y2=currentReferenceHigh,
                     xloc=xloc.bar_index,
                     extend=extend.none,
                     color=color.new(color.green, 35),
                     width=2)
            else
                line.set_xy1(currentHighLine, bar_index, currentReferenceHigh)
                line.set_xy2(currentHighLine, bar_index + 3, currentReferenceHigh)
        else
            if not na(currentHighLine)
                line.delete(currentHighLine)
                currentHighLine := na
 
        // Reference low
        if not na(currentReferenceLow)
            if na(currentLowLine)
                currentLowLine := line.new(
                     x1=bar_index,
                     y1=currentReferenceLow,
                     x2=bar_index + 3,
                     y2=currentReferenceLow,
                     xloc=xloc.bar_index,
                     extend=extend.none,
                     color=color.new(color.red, 35),
                     width=2)
            else
                line.set_xy1(currentLowLine, bar_index, currentReferenceLow)
                line.set_xy2(currentLowLine, bar_index + 3, currentReferenceLow)
        else
            if not na(currentLowLine)
                line.delete(currentLowLine)
                currentLowLine := na
    else
        if not na(currentHighLine)
            line.delete(currentHighLine)
            currentHighLine := na
 
        if not na(currentLowLine)
            line.delete(currentLowLine)
            currentLowLine := na
 
// Liquidity sweep arrows
plotshape(
     showSweep and bullishSweep,
     title="Bullish Liquidity Sweep",
     location=location.belowbar,
     color=sweepBullColor,
     style=shape.arrowup,
     size=size.small)
 
plotshape(
     showSweep and bearishSweep,
     title="Bearish Liquidity Sweep",
     location=location.abovebar,
     color=sweepBearColor,
     style=shape.arrowdown,
     size=size.small)
 
// Breakout and breakdown signals
plotshape(
     bullishBreakout,
     title="Bullish Breakout",
     location=location.belowbar,
     color=color.green,
     style=shape.triangleup,
     size=size.tiny)
 
plotshape(
     bearishBreakout,
     title="Bearish Breakdown",
     location=location.abovebar,
     color=color.red,
     style=shape.triangledown,
     size=size.tiny)
 
// Moving averages
plot(
     show_mas ? ma1 : na,
     title="MA 1",
     color=ma1_color,
     linewidth=2)
 
plot(
     show_mas ? ma2 : na,
     title="MA 2",
     color=ma2_color,
     linewidth=2)
 
plot(
     show_mas ? ma3 : na,
     title="MA 3",
     color=ma3_color,
     linewidth=2)
 
//═════════════════════════════════════════════════════════════════════════════
// 8. ALERT CONDITIONS
//═════════════════════════════════════════════════════════════════════════════
 
alertcondition(
     bullishBreakout,
     title="Engulfing Reference High Breakout",
     message="Bullish breakout condition met above the engulfing reference high.")
 
alertcondition(
     bearishBreakout,
     title="Engulfing Reference Low Breakdown",
     message="Bearish breakdown condition met below the engulfing reference low.")
 
alertcondition(
     bullishSweep,
     title="Bullish Liquidity Sweep",
     message="Bullish liquidity sweep condition met below the previous candle low.")
 
alertcondition(
     bearishSweep,
     title="Bearish Liquidity Sweep",
     message="Bearish liquidity sweep condition met above the previous candle high.")

← 返回列表