Turtle Soup Model [PhenLabs]

PhenLabs · study · 314 行 · 点赞 477 · TradingView 原页

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

Pine Script

// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © PhenLabs
 
//@version=6
indicator('Turtle Soup Model [PhenLabs]', shorttitle = 'PhenLabs - TS', overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
//  Structure Settings   
comparisonSymbol = input.symbol('ES1!', 'Comparison Symbol', inline = 'compareSymbol', tooltip = 'Reference symbol used for comparative market structure analysis. The indicator identifies divergences between the main and comparison symbols.', group = 'Structure Settings')
pivotPeriod = input.int(3, 'Pivot', minval = 2, tooltip = 'Number of bars used to identify pivot points. Lower values are more sensitive to shorter-term structures, while higher values identify major structures. Recommended range: 2-5 for intraday, 3-7 for daily charts.', group = 'Structure Settings')
useComparison = true
structureHighColor = input.color(#ff1100, 'High Structure', tooltip = 'Color for highlighting high market structures. These represent potential resistance levels where price and comparison symbol show divergence.', group = 'Style Settings')
structureLowColor = input.color(#2157f3, 'Low Structure', tooltip = 'Color for highlighting low market structures. These represent potential support levels where price and comparison symbol show divergence.', group = 'Style Settings')
bullishColor = input.color(color.new(#5dad6033, 80), 'Bullish Gap Color', tooltip = 'Color for highlighting bullish gaps. These occur when the current low is higher than the previous high, indicating potential upward momentum.', group = 'Style Settings')
bearishColor = input.color(color.new(#b85252, 80), 'Bearish Gap Color', tooltip = 'Color for highlighting bearish gaps. These occur when the current high is lower than the previous low, indicating potential downward momentum.', group = 'Style Settings')
structureWidth = input.int(2, 'Line Width', minval = 1, maxval = 4, tooltip = 'Thickness of structure lines. Higher values make the lines more visible but may create visual clutter. Recommended: 2 for most charts.', group = 'Style Settings')
//  Gap Settings  
signalMode = input.string('Close', title = 'Source', options = ['Close', 'Wick'], tooltip = 'Determines how gaps are measured: "Close" uses closing prices only, while "Wick" includes the entire price range (high/low). "Close" is more conservative, "Wick" captures more potential signals.', group = 'Gap Settings')
atrMultiplier = 0
 
//  Colors   
midlineColor = color.new(color.gray, 80)
transparentColor = color.rgb(0, 0, 0, 100)
 
//  Core Variables   
currentBar = bar_index
getPriceLevels() =>
    [high, low, close]
 
//  Structure Arrays   
var array<float> highStructureLevels = array.new_float()
var array<float> lowStructureLevels = array.new_float()
var array<float> comparisonHighLevels = array.new_float()
var array<float> comparisonLowLevels = array.new_float()
var array<int> structureHighBars = array.new_int()
var array<int> structureLowBars = array.new_int()
var maxBarDistance = 5
 
//  Helper Functions   
getBarFromTime(t) =>
    int resultBar = 0
    if not na(t)
        resultBar := bar_index
        for i = 0 to 499 by 1
            if time[i] == t
                resultBar := i
                break
    resultBar
 
//  Type Definitions   
type SignalPoint
	int time
	float price
	int direction
 
type GapStructure
	int leftBar = na
	float topLevel = na
	int rightBar = na
	float bottomLevel = na
	float middleLevel = na
	int direction = na
	int status = na
	array<SignalPoint> signals = na
	int valueTime = na
	bool isRendered = false
 
//  Gap Variables   
useWicks = signalMode == 'Wick'
arrayLimit = 100
topPrice = math.max(open, close)
bottomPrice = math.min(open, close)
 
var bullishGaps = array.new<GapStructure>()
var bearishGaps = array.new<GapStructure>()
var bullishInversions = array.new<GapStructure>()
var bearishInversions = array.new<GapStructure>()
 
//  Gap Management   
processGaps(gapArray, inversionArray) =>
    if array.size(gapArray) >= arrayLimit
        array.shift(gapArray)
 
    if array.size(gapArray) > 0
        for i = array.size(gapArray) - 1 to 0 by 1
            gap = array.get(gapArray, i)
            dir = gap.direction
 
            if dir == 1 and bottomPrice < gap.bottomLevel
                gap.valueTime := time
                array.push(inversionArray, array.remove(gapArray, i))
            if dir == -1 and topPrice > gap.topLevel
                gap.valueTime := time
                array.push(inversionArray, array.remove(gapArray, i))
 
processInversions(invArray) =>
    signal = false
    if array.size(invArray) >= arrayLimit
        array.shift(invArray)
    if array.size(invArray) > 0
        for i = array.size(invArray) - 1 to 0 by 1
            inv = array.get(invArray, i)
            topLevel = inv.topLevel
            bottomLevel = inv.bottomLevel
            dir = inv.direction
            currentStatus = inv.status
 
            if currentStatus == 0 and dir == 1
                inv.status := 1
                inv.direction := -1
                inv.direction
            if dir == -1 and currentStatus == 0
                inv.status := 1
                inv.direction := 1
                inv.direction
            if currentStatus >= 1
                inv.rightBar := time
                inv.rightBar
            if dir == -1 and currentStatus == 1 and close < bottomLevel and (useWicks ? high : close[1]) >= bottomLevel and (useWicks ? high : close[1]) < topLevel
                array.push(inv.signals, SignalPoint.new(time, topLevel, -1))
                signal := true
                signal
            if dir == 1 and currentStatus == 1 and close > topLevel and (useWicks ? low : close[1]) <= topLevel and (useWicks ? low : close[1]) > bottomLevel
                array.push(inv.signals, SignalPoint.new(time, bottomLevel, 1))
                signal := true
                signal
            if currentStatus >= 1 and (dir == -1 and topPrice > topLevel or dir == 1 and bottomPrice < bottomLevel)
                array.remove(invArray, i)
    signal
 
renderStructures(structureArray) =>
    for [index, structure] in structureArray
        if not structure.isRendered // Only render if not already drawn  
            topLevel = structure.topLevel
            bottomLevel = structure.bottomLevel
            leftBar = structure.leftBar
            valueTime = structure.valueTime
            middleLevel = structure.middleLevel
            mainColor = structure.direction == -1 ? bullishColor : bearishColor
            invColor = structure.direction == -1 ? bearishColor : bullishColor
 
            gapBar = bar_index - getBarFromTime(leftBar)
            nearStructure = false
 
            if array.size(structureHighBars) > 0
                for i = 0 to array.size(structureHighBars) - 1 by 1
                    structureBar = array.get(structureHighBars, i)
                    if math.abs(gapBar - structureBar) <= 8
                        nearStructure := true
                        break
 
            if not nearStructure and array.size(structureLowBars) > 0
                for i = 0 to array.size(structureLowBars) - 1 by 1
                    structureBar = array.get(structureLowBars, i)
                    if math.abs(gapBar - structureBar) <= 8
                        nearStructure := true
                        break
 
            if nearStructure
                box.new(leftBar, topLevel, valueTime, bottomLevel, bgcolor = mainColor, border_color = transparentColor, xloc = xloc.bar_time)
                box.new(valueTime, topLevel, time, bottomLevel, bgcolor = invColor, border_color = transparentColor, xloc = xloc.bar_time)
                line.new(leftBar, middleLevel, time, middleLevel, color = midlineColor, style = line.style_dashed, xloc = xloc.bar_time)
                structure.isRendered := true // Mark as rendered  
                structure.isRendered
 
//  Structure Analysis   
analyzeStructure(isHigh, currentLevel, comparisonLevel) =>
    var float previousLevel = na
    var float previousCompLevel = na
    var int previousBar = na
    var bool divergence = false
 
    if currentLevel != currentLevel[1] and comparisonLevel != comparisonLevel[1]
        float mainMovement = currentLevel - previousLevel
        float compMovement = comparisonLevel - previousCompLevel
 
        if not na(mainMovement) and not na(compMovement)
            if isHigh
                if mainMovement > 0 and compMovement < 0
                    line.new(x1 = previousBar, y1 = previousLevel, x2 = currentBar[pivotPeriod], y2 = previousLevel, color = structureHighColor, width = structureWidth)
                    array.push(highStructureLevels, currentLevel)
                    array.push(comparisonHighLevels, comparisonLevel)
                    array.push(structureHighBars, bar_index)
                    divergence := true
                    divergence
            else
                if mainMovement < 0 and compMovement > 0
                    line.new(x1 = previousBar, y1 = previousLevel, x2 = currentBar[pivotPeriod], y2 = previousLevel, color = structureLowColor, width = structureWidth)
                    array.push(lowStructureLevels, currentLevel)
                    array.push(comparisonLowLevels, comparisonLevel)
                    array.push(structureLowBars, bar_index)
                    divergence := true
                    divergence
 
        previousCompLevel := comparisonLevel
        previousLevel := currentLevel
        previousBar := currentBar[pivotPeriod]
        previousBar
    else if isHigh and currentLevel > currentLevel[1] or not isHigh and currentLevel < currentLevel[1]
        previousCompLevel := comparisonLevel
        previousLevel := currentLevel
        previousBar := currentBar[pivotPeriod]
        previousBar
 
    divergence
 
//  Main Logic   
// Clear old drawings  
if barstate.isfirst
    for boxes in box.all
        box.delete(boxes)
    for lines in line.all
        line.delete(lines)
    for labels in label.all
        label.delete(labels)
 
pivotHigh = fixnan(ta.pivothigh(pivotPeriod, pivotPeriod))
pivotLow = fixnan(ta.pivotlow(pivotPeriod, pivotPeriod))
[compHigh, compLow, compClose] = request.security(comparisonSymbol, timeframe.period, getPriceLevels())
 
var bool highStructureSwept = false
var bool lowStructureSwept = false
highStructureSwept := false
lowStructureSwept := false
 
if useComparison
    compPivotHigh = fixnan(ta.pivothigh(compHigh, pivotPeriod, pivotPeriod))
    compPivotLow = fixnan(ta.pivotlow(compLow, pivotPeriod, pivotPeriod))
 
    analyzeStructure(true, pivotHigh, compPivotHigh)
    analyzeStructure(false, pivotLow, compPivotLow)
 
    if array.size(highStructureLevels) > 0
        for i = array.size(highStructureLevels) - 1 to 0 by 1
            mainLevel = array.get(highStructureLevels, i)
            compLevel = array.get(comparisonHighLevels, i)
 
            if high > mainLevel and compHigh <= compLevel
                highStructureSwept := true
                array.remove(highStructureLevels, i)
                array.remove(comparisonHighLevels, i)
                array.remove(structureHighBars, i)
 
    if array.size(lowStructureLevels) > 0
        for i = array.size(lowStructureLevels) - 1 to 0 by 1
            mainLevel = array.get(lowStructureLevels, i)
            compLevel = array.get(comparisonLowLevels, i)
 
            if low < mainLevel and compLow >= compLevel
                lowStructureSwept := true
                array.remove(lowStructureLevels, i)
                array.remove(comparisonLowLevels, i)
                array.remove(structureLowBars, i)
 
// Gap Detection and Processing  
atrValue = nz(ta.atr(200) * atrMultiplier, ta.cum(high - low) / (bar_index + 1))
 
gapUp = low > high[2] and close[1] > high[2]
gapDown = high < low[2] and close[1] < low[2]
 
if gapUp and math.abs(low - high[2]) > atrValue
    array.push(bullishGaps, GapStructure.new(time[1], low, time, high[2], math.avg(low, high[2]), 1, 0, array.new<SignalPoint>(), na, false))
 
if gapDown and math.abs(low[2] - high) > atrValue
    array.push(bearishGaps, GapStructure.new(time[1], low[2], time, high, math.avg(high, low[2]), -1, 0, array.new<SignalPoint>(), na, false))
 
processGaps(bullishGaps, bullishInversions)
processGaps(bearishGaps, bearishInversions)
 
bearSignal = processInversions(bullishInversions)
bullSignal = processInversions(bearishInversions)
 
if barstate.islast
    renderStructures(bullishInversions)
    renderStructures(bearishInversions)
 
// Alert Settings  
showAlerts = true
alertMessage = 'Structure Break Alert on {{ticker}}'
 
// Alert tracking  
var bool alertedHigh = false
var bool alertedLow = false
 
// Alert Processing  
if showAlerts
    if array.size(highStructureLevels) > 0
        for i = 0 to array.size(highStructureLevels) - 1 by 1
            mainLevel = array.get(highStructureLevels, i)
            compLevel = array.get(comparisonHighLevels, i)
            if high > mainLevel and compHigh <= compLevel and not alertedHigh
                alert(alertMessage + '\nHigh Structure Break at ' + str.tostring(mainLevel), alert.freq_once_per_bar_close)
                alertedHigh := true
                alertedHigh
 
    if array.size(lowStructureLevels) > 0
        for i = 0 to array.size(lowStructureLevels) - 1 by 1
            mainLevel = array.get(lowStructureLevels, i)
            compLevel = array.get(comparisonLowLevels, i)
            if low < mainLevel and compLow >= compLevel and not alertedLow
                alert(alertMessage + '\nLow Structure Break at ' + str.tostring(mainLevel), alert.freq_once_per_bar_close)
                alertedLow := true
                alertedLow
 
// Reset alert flags on new structures  
if array.size(highStructureLevels) != array.size(highStructureLevels)[1]
    alertedHigh := false
    alertedHigh
if array.size(lowStructureLevels) != array.size(lowStructureLevels)[1]
    alertedLow := false
    alertedLow
 
// Alert Conditions  
alertcondition(highStructureSwept, 'High Structure Break', 'Price broke above high structure while comparison remained below')
alertcondition(lowStructureSwept, 'Low Structure Break', 'Price broke below low structure while comparison remained above')

← 返回列表