Fractal Pullback Market Structure

The_Forex_Steward · study · 327 行 · 点赞 1,074 · 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/
// © The_Forex_Steward
 
//@version=6
indicator("Fractal Pullback Market Structure", overlay=true)
 
// === User Inputs ==
x = input.int(4, title="Lookback Period")
multiplier = input.int(1, title = "Timeframe Multiplier (e.g. 1hr x 24 = D timeframe)")
useSafeOffsetLimit = input.bool(true, title="Use Safe History Offset Limit?")
maxSafeOffset      = input.int(550, title="Max Safe History Offset", minval=50, tooltip="Caps how far back we look to avoid buffer overflow errors.")
zigzagLineColor = input.color(color.black, title="ZigZag Line Color")
zigzagLineWidth = input.int(3, title="ZigZag Line Width", minval=1, maxval= 10)
zigzagLineStyle = input.string("Solid", title="ZigZag Line Style", options=["Solid", "Dotted", "Dashed"])
bosBullishLineColor = input.color(color.green, title="Bullish BOS Line Color")
bosBearishLineColor = input.color(color.red, title="Bearish BOS Line Color")
bosLineWidth = input.int(2, minval=1, maxval=10, title="BOS Line Width")
bosLineStyle = input.string("Dotted", title="BOS Line Style", options=["Solid", "Dotted", "Dashed"])
bosLineStyleConst = bosLineStyle == "Solid" ? line.style_solid : bosLineStyle == "Dotted" ? line.style_dotted : line.style_dashed
hhBackgroundColor = color.rgb(76, 175, 79, 100)
hhTextColor = color.green
lhBackgroundColor = color.rgb(0, 137, 123, 100)
lhTextColor = color.red
llBackgroundColor = color.rgb(255, 82, 82, 100)
llTextColor = color.red
hlBackgroundColor = color.rgb(255, 153, 0, 100)
hlTextColor = color.green
alertMode = input.string("MTF", title= "Enable/Disable for Any Alert() Function Call↓ Alert Status→", options= ["LTF", "MTF", "HTF"])
alertHighsandLows = input.bool(true, title= "Swing Highs & Lows")
alertBoS = input.bool(true, title= "BoS")
 
pullBackMultiple = multiplier*x
 
// === Bearish Pullback Condition ===
// high must be greater than all highs in last x bars
bearishPullback = high[pullBackMultiple] > ta.highest(high, pullBackMultiple - 1)
 
// === Bullish Pullback Condition ===
// low must be lower than all lows in last x bars
bullishPullback = low[pullBackMultiple] < ta.lowest(low, pullBackMultiple - 1)
 
var float swingpointLow = na
var float swingpointHigh = na
var int swingpointHighIndex = na
var int swingpointLowIndex = na
 
if bullishPullback
    swingpointLow := ta.lowest(low, pullBackMultiple)
    swingpointLowIndex := bar_index[pullBackMultiple]
 
if bearishPullback
    swingpointHigh := ta.highest(high, pullBackMultiple)
    swingpointHighIndex := bar_index[pullBackMultiple]
 
// === Internal Structure Logic ===
var int bullishCount = 0
var int bearishCount = 0
var float lowestBullishPrice = na
var float highestBearishPrice = na
var float firstBullishOpen = na
var float firstBearishOpen = na
var int lastInternalShift = 0
var int lastLowIndex = na
var int lastHighIndex = na
var float lastSwingHigh = na
var float lastSwingLow = na
var float lastBullishInternalShiftPrice = na
var float lastBearishInternalShiftPrice = na
var float currentSwingHigh = na
var int currentSwingHighIndex = na
var float currentSwingLow = na
var int currentSwingLowIndex = na
var float prevSwingHigh = na
var float prevSwingLow = na
var bool isHH = false
var bool isHL = false
var bool isLL = false
var bool isLH = false
var bool isLiquiditySweep = false
var float lastOpposingLow = na  // For HH
var float lastOpposingHigh = na // For LL
var bool bullishBOSOccurred = false
var bool bearishBOSOccurred = false
 
internalShiftBullish = bullishPullback
internalShiftBearish = bearishPullback
 
allowInternalShiftBearish = internalShiftBearish and lastInternalShift != -1
allowInternalShiftBullish = internalShiftBullish and lastInternalShift != 1
 
var bool plotBearishInternalShift = false
var bool plotBullishInternalShift = false
 
// === Determine Internal Shift Based on User Input ===
plotBearishInternalShift := false
plotBullishInternalShift := false
 
if allowInternalShiftBearish
    plotBearishInternalShift := true
    lastInternalShift := -1
 
if allowInternalShiftBullish
    plotBullishInternalShift := true
    lastInternalShift := 1
 
// === Plot internal shift markers ===
plotshape(plotBullishInternalShift, title="Bullish Internal Shift", location=location.belowbar, color=color.rgb(54, 58, 69, 75), style=shape.triangleup, size=size.tiny)
plotshape(plotBearishInternalShift, title="Bearish Internal Shift", location=location.abovebar, color=color.rgb(54, 58, 69, 75), style=shape.triangledown, size=size.tiny)
 
// === Persistent variables for multiple line handling ===
var line[] zigzagLines = array.new<line>()
var int lastBearishShiftBar = na
var int lastBullishShiftBar = na
var float lastZigzagPrice = na
var string lastSwingType = ""
 
// Save shift bar indices
if plotBearishInternalShift
    lastBearishShiftBar := bar_index
if plotBullishInternalShift
    lastBullishShiftBar := bar_index
 
// === Track Break of Structure (BOS) markers ===
// Initialize flags as mutable var variables
var bool plotBullishBOS = false
var bool plotBearishBOS = false
 
// === Conditions to plot the BOS markers ===
// Bullish BOS (Only plot the first candle breaking the swing high)
if not na(lastSwingHigh) and close > lastSwingHigh and not plotBullishBOS
    plotBullishBOS := true
 
// Bearish BOS (Only plot the first candle breaking the swing low)
if not na(lastSwingLow) and close < lastSwingLow and not plotBearishBOS
    plotBearishBOS := true  // Set the flag to true after the first BOS
 
// Modify these flags
var line bullishBOSLine = na
var line bearishBOSLine = na
 
// === Plot Break of Structure (BOS) with horizontal lines ===
 
// === Conditions to plot the BOS markers ===
// Bullish BOS (Previous candle must open below the swing high, current breaks it)
if not na(lastSwingHigh) and open[1] < lastSwingHigh and close > lastSwingHigh and na(bullishBOSLine)
    bullishBOSOccurred := true
    bullishBOSLine := line.new(x1=lastHighIndex, y1=lastSwingHigh, x2=bar_index, y2=lastSwingHigh, color=bosBullishLineColor, width= bosLineWidth, style=bosLineStyleConst)
    lastSwingHigh := na
 
// Bearish BOS (Previous candle must open above the swing low, current breaks it)
if not na(lastSwingLow) and open[1] > lastSwingLow and close < lastSwingLow and na(bearishBOSLine)
    bearishBOSOccurred := true
    bearishBOSLine := line.new(x1=lastLowIndex, y1=lastSwingLow, x2=bar_index, y2=lastSwingLow, color=bosBearishLineColor, width=bosLineWidth, style=bosLineStyleConst)
    lastSwingLow := na
 
// Optionally reset lines after new swings are formed, if needed
if close < lastSwingHigh
    bullishBOSLine := na  // Reset bullish BOS line when a new swing high is formed
 
if close > lastSwingLow
    bearishBOSLine := na  // Reset bearish BOS line when a new swing low is formed
 
// Bearish shift followed by Bullish shift → Track lowest low
if plotBullishInternalShift and not na(lastBearishShiftBar)
    shiftLength = bar_index - swingpointHighIndex
    loopLimit = useSafeOffsetLimit ? math.min(shiftLength, maxSafeOffset) : shiftLength
    if shiftLength <= 10000
        lowest = low
        lowIndex = bar_index
        for i = 0 to loopLimit
            if low[i] < lowest
                lowest := low[i]
                lowIndex := bar_index - i
 
        // Plot zigzag line
                // Plot zigzag line for LL and HL separately
        if not na(prevSwingLow)
            if lowest < prevSwingLow  // LL
                if zigzagLineStyle == "Solid"
                    line.new(x1=lastHighIndex, y1=prevSwingHigh, x2=lowIndex, y2=lowest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
                else if zigzagLineStyle == "Dotted"
                    line.new(x1=lastHighIndex, y1=prevSwingHigh, x2=lowIndex, y2=lowest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
                else if zigzagLineStyle == "Dashed"
                    line.new(x1=lastHighIndex, y1=prevSwingHigh, x2=lowIndex, y2=lowest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
 
            else  // LH
                if zigzagLineStyle == "Solid"
                    line.new(x1=lastHighIndex, y1=prevSwingHigh, x2=lowIndex, y2=lowest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
                else if zigzagLineStyle == "Dotted"
                    line.new(x1=lastHighIndex, y1=prevSwingHigh, x2=lowIndex, y2=lowest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
                else if zigzagLineStyle == "Dashed"
                    line.new(x1=lastHighIndex, y1=prevSwingHigh, x2=lowIndex, y2=lowest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
 
 
        // Update swing low and plot label (HL or LL)
        if not na(prevSwingLow)
            isLL := not na(prevSwingLow) and lowest < prevSwingLow
            isHL := not na(prevSwingLow) and lowest > prevSwingLow
        if isLL
            label.new(lowIndex, lowest, "LL", color=llBackgroundColor, style=label.style_label_up, textcolor=llTextColor, size=size.small)
        if isHL
            label.new(lowIndex, lowest, "HL", color=hlBackgroundColor, style=label.style_label_up, textcolor=hlTextColor, size=size.small)
        lastOpposingHigh := prevSwingHigh
 
        prevSwingLow := lowest
 
        lastZigzagPrice := lowest
        lastSwingLow := lowest
        lastLowIndex := lowIndex
        lastBearishShiftBar := bar_index
 
// Bullish shift followed by Bearish shift → Track highest high
if plotBearishInternalShift and not na(lastBullishShiftBar)
    shiftLength = bar_index - swingpointLowIndex
    loopLimit = useSafeOffsetLimit ? math.min(shiftLength, maxSafeOffset) : shiftLength
    if shiftLength <= 10000
        highest = high
        highIndex = bar_index
        for i = 0 to loopLimit
            if high[i] > highest
                highest := high[i]
                highIndex := bar_index - i
 
        // Plot zigzag line
        if not na(prevSwingHigh)
            if highest > prevSwingHigh  // HH
                if zigzagLineStyle == "Solid"
                    line.new(x1=lastLowIndex, y1=prevSwingLow, x2=highIndex, y2=highest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
                else if zigzagLineStyle == "Dotted"
                    line.new(x1=lastLowIndex, y1=prevSwingLow, x2=highIndex, y2=highest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
                else if zigzagLineStyle == "Dashed"
                    line.new(x1=lastLowIndex, y1=prevSwingLow, x2=highIndex, y2=highest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
 
            else  // LH
                if zigzagLineStyle == "Solid"
                    line.new(x1=lastLowIndex, y1=prevSwingLow, x2=highIndex, y2=highest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_solid)
                else if zigzagLineStyle == "Dotted"
                    line.new(x1=lastLowIndex, y1=prevSwingLow, x2=highIndex, y2=highest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dotted)
                else if zigzagLineStyle == "Dashed"
                    line.new(x1=lastLowIndex, y1=prevSwingLow, x2=highIndex, y2=highest, color=zigzagLineColor, width=zigzagLineWidth, style=line.style_dashed)
 
        // Update swing high and plot label (HH or LH)
        if not na(prevSwingHigh)
            isHH := not na(prevSwingHigh) and highest > prevSwingHigh
            isLH := not na(prevSwingHigh) and highest < prevSwingHigh
        if isHH
            label.new(highIndex, highest, "HH", color=hhBackgroundColor, style=label.style_label_down, textcolor=hhTextColor, size=size.small)
        if isLH
            label.new(highIndex, highest, "LH", color=lhBackgroundColor, style=label.style_label_down, textcolor=lhTextColor, size=size.small)
            lastOpposingLow := prevSwingLow
 
        prevSwingHigh := highest
 
        lastZigzagPrice := highest
        lastSwingHigh := highest
        lastHighIndex := highIndex
        lastBullishShiftBar := bar_index
 
 
// === Alerts ===
alertcondition(not na(lastSwingHigh) and open[1] < lastSwingHigh and close > lastSwingHigh, title="Bullish Break of Structure", message="Bullish Break of Structure detected!")
alertcondition(not na(lastSwingLow) and open[1] > lastSwingLow and close < lastSwingLow, title="Bearish Break of Structure", message="Bearish Break of Structure detected!")
alertcondition(isHH and plotBearishInternalShift, title="Higher High (HH)", message="Higher High (HH) detected")
alertcondition(isHL and plotBullishInternalShift, title="Higher Low (HL)", message="Higher Low (HL) detected")
alertcondition(isLL and plotBullishInternalShift, title="Lower Low (LL)", message="Lower Low (LL) detected")
alertcondition(isLH and plotBearishInternalShift, title="Lower High (LH)", message="Lower High (LH) detected")
alertcondition((isLiquiditySweep and isLL and plotBullishInternalShift) or (isLiquiditySweep and isHH and plotBearishInternalShift), title="Liquidity Sweep (LS)", message="Liquidity Sweep (LS) detected")
 
// === Alerts ===
if alertMode == "LTF"
    if isHH and plotBearishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
        alert("Higher High (HH) detected (LTF)", alert.freq_once_per_bar_close)
 
    if isHL and plotBullishInternalShift and (alertHighsandLows == true)
        alert("Higher Low (HL) detected (LTF)", alert.freq_once_per_bar_close)
 
    if isLL and plotBullishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
        alert("Lower Low (LL) detected (LTF)" , alert.freq_once_per_bar_close)
 
    if isLH and plotBearishInternalShift and (alertHighsandLows == true)
        alert("Lower High (LH) detected (LTF)", alert.freq_once_per_bar_close)
 
    if bullishBOSOccurred and (alertBoS == true)
        alert("Bullish BoS detected. (LTF)", alert.freq_once_per_bar_close)
 
    if bearishBOSOccurred and (alertBoS == true)
        alert("Bearish BoS detected. (LTF)", alert.freq_once_per_bar_close)
 
if alertMode == "MTF"
    if isHH and plotBearishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
        alert("Higher High (HH) detected (MTF)", alert.freq_once_per_bar_close)
 
    if isHL and plotBullishInternalShift and (alertHighsandLows == true)
        alert("Higher Low (HL) detected (MTF)", alert.freq_once_per_bar_close)
 
    if isLL and plotBullishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
        alert("Lower Low (LL) detected (MTF)" , alert.freq_once_per_bar_close)
 
    if isLH and plotBearishInternalShift and (alertHighsandLows == true)
        alert("Lower High (LH) detected (MTF)", alert.freq_once_per_bar_close)
 
    if bullishBOSOccurred and (alertBoS == true)
        alert("Bullish BoS detected. (MTF)", alert.freq_once_per_bar_close)
 
    if bearishBOSOccurred and (alertBoS == true)
        alert("Bearish BoS detected. (MTF)", alert.freq_once_per_bar_close)
 
 
 
if alertMode == "HTF"
    if isHH and plotBearishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
        alert("Higher High (HH) detected (HTF)", alert.freq_once_per_bar_close)
 
    if isHL and plotBullishInternalShift and (alertHighsandLows == true)
        alert("Higher Low (HL) detected (HTF)", alert.freq_once_per_bar_close)
 
    if isLL and plotBullishInternalShift and not isLiquiditySweep and (alertHighsandLows == true)
        alert("Lower Low (LL) detected (HTF)" , alert.freq_once_per_bar_close)
 
    if isLH and plotBearishInternalShift and (alertHighsandLows == true)
        alert("Lower High (LH) detected (HTF)", alert.freq_once_per_bar_close)
 
    if bullishBOSOccurred and (alertBoS == true)
        alert("Bullish BoS detected. (HTF)", alert.freq_once_per_bar_close)
 
    if bearishBOSOccurred and (alertBoS == true)
        alert("Bearish BoS detected. (HTF)", alert.freq_once_per_bar_close)

← 返回列表