//@version=6 indicator("Engulfing Pattern Breakout MTF", overlay=true,…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
//@version=6 indicator("Engulfing Pattern Breakout MTF", overlay=true, max_boxes_count=100, max_lines_count=100, max_labels_count = 100)
// =================== Inputs =================== // Group: Pattern Detection group_pattern = "Pattern Detection Settings" htfInput = input.timeframe("", "Higher Timeframe (Leave empty for chart TF)", group = group_pattern) showEngulfingShape = input.bool(true, "Show Engulfing Markers", group = group_pattern)
// Group: Visuals group_visuals = "Visual Settings" showRectangle = input.bool(true, "Show Engulfing Range Rectangle", group = group_visuals) showMidLine = input.bool(true, "Show Range Midpoint Line (POC Proxy)", group = group_visuals) showBreakoutLabel = input.bool(true, "Show Breakout Labels", group = group_visuals)
bullColor = input.color(color.new(color.green, 70), "Bullish Color", group = group_visuals) bearColor = input.color(color.new(color.red, 70), "Bearish Color", group = group_visuals) midLineColor = input.color(color.new(color.blue, 50), "Midpoint Line Color", group = group_visuals) midLineStyleOption = input.string("Dashed", "Midpoint Line Style", options=["Solid", "Dotted", "Dashed"], group = group_visuals) breakoutLabelColor = input.color(color.new(color.orange, 0), "Breakout Label Color", group = group_visuals)
// =================== Data Structure =================== type EngulfingInfo int id int detectedBarIndex float rangeHigh float rangeLow bool isBullish box rectangle line midLine bool isBroken label breakoutLabel
// =================== Variables =================== var engulfingPatterns = array.new() var int patternIdCounter = 0
getLineStyle(styleString) => switch styleString "Solid" => line.style_solid "Dotted" => line.style_dotted "Dashed" => line.style_dashed => line.style_solid
midLineStyle = getLineStyle(midLineStyleOption)
// =================== MTF Data Fetching =================== useHtf = htfInput != "" targetTimeframe = useHtf ? htfInput : timeframe.period [htfOpen, htfHigh, htfLow, htfClose, htfTime] = request.security(syminfo.tickerid, targetTimeframe, [open, high, low, close, time], lookahead=barmerge.lookahead_on)
// =================== Engulfing Detection Logic =================== isBullishEngulfing(o, c, o1, c1) => o1 > c1 and c > o and c > o1 and o < c1
isBearishEngulfing(o, c, o1, c1) => c1 > o1 and o > c and o > c1 and c < o1
htfOpen1 = htfOpen[1] htfClose1 = htfClose[1] isNewHtfBar = ta.change(htfTime) != 0
bullEngulfingDetected = isNewHtfBar and isBullishEngulfing(htfOpen, htfClose, htfOpen1, htfClose1) bearEngulfingDetected = isNewHtfBar and isBearishEngulfing(htfOpen, htfClose, htfOpen1, htfClose1)
// =================== Pattern Management =================== if bullEngulfingDetected or bearEngulfingDetected patternIdCounter += 1 float midPoint = (htfHigh + htfLow) / 2 bool isBull = bullEngulfingDetected
box_ = showRectangle ? box.new(
left = bar_index,
top = htfHigh,
right = bar_index + 1,
bottom = htfLow,
bgcolor = isBull ? bullColor : bearColor,
border_color = na,
extend = extend.right
) : na
line_ = showMidLine ? line.new(
x1 = bar_index,
y1 = midPoint,
x2 = bar_index + 1,
y2 = midPoint,
color = midLineColor,
style = midLineStyle,
width = 1,
extend = extend.right
) : na
newPattern = EngulfingInfo.new(
id = patternIdCounter,
detectedBarIndex = bar_index,
rangeHigh = htfHigh,
rangeLow = htfLow,
isBullish = isBull,
rectangle = box_,
midLine = line_,
isBroken = false,
breakoutLabel = na
)
engulfingPatterns.push(newPattern)
// =================== Check Breakouts and Manage Objects =================== if engulfingPatterns.size() > 0 for i = engulfingPatterns.size() - 1 to 0 by -1 pattern = engulfingPatterns.get(i)
if pattern.isBroken
continue
breakCondition = false
labelText = ""
if pattern.isBullish and close > pattern.rangeHigh
breakCondition := true
labelText := "▲ Breakout"
else if not pattern.isBullish and close < pattern.rangeLow
breakCondition := true
labelText := "▼ Breakout"
if breakCondition
pattern.isBroken := true
if showRectangle and not na(pattern.rectangle)
pattern.rectangle.set_extend(extend.none)
pattern.rectangle.set_right(bar_index)
if showMidLine and not na(pattern.midLine)
pattern.midLine.set_extend(extend.none)
pattern.midLine.set_x2(bar_index)
if showBreakoutLabel
labelY = pattern.isBullish ? pattern.rangeHigh : pattern.rangeLow
labelStyle = pattern.isBullish ? label.style_label_down : label.style_label_up
newLabel = label.new(bar_index, labelY, labelText,
color = color.new(color.black, 100),
textcolor = breakoutLabelColor,
style = labelStyle,
size = size.small)
pattern.breakoutLabel := newLabel
// =================== Plot Shapes (Fixed) =================== plotshape( showEngulfingShape and bullEngulfingDetected, title = "Bullish Engulfing", location = location.belowbar, color = color.green, style = shape.triangleup, size = size.small )
plotshape( showEngulfingShape and bearEngulfingDetected, title = "Bearish Engulfing", location = location.abovebar, color = color.red, style = shape.triangledown, size = size.small )
This is a well-structured Pine Script (version 6) indicator for detecting engulfing patterns on multiple timeframes (MTF) and visualizing breakouts. Let me break down the code, explain its functionality, and provide some suggestions for improvement or optimization.
The indicator identifies bullish and bearish engulfing patterns on a user-specified timeframe (or the chart's timeframe if none is specified). It then:
The script uses Pine Script's object-oriented features (like type, box, line, and label) to manage patterns and their visual elements.
Pattern Detection Settings:
htfInput: Allows users to specify a higher timeframe (MTF) for pattern detection. If left empty, it uses the chart's timeframe.showEngulfingShape: Toggles the display of triangle markers for engulfing patterns.Visual Settings:
showRectangle: Toggles the display of rectangles around engulfing ranges.showMidLine: Toggles the display of a midpoint line within the range.showBreakoutLabel: Toggles the display of breakout labels.EngulfingInfo)The script defines a custom type EngulfingInfo to store information about each detected engulfing pattern, including:
id: Unique identifier for the pattern.detectedBarIndex: Bar index where the pattern was detected.rangeHigh and rangeLow: High and low of the engulfing range.isBullish: Whether the pattern is bullish or bearish.rectangle, midLine, breakoutLabel: Visual elements associated with the pattern.isBroken: Whether the range has been broken.Mismatched input "end of line without line continuation" expecting ")"
The error message "Mismatched input 'end of line without line continuation' expecting ')'" in Pine Script typically indicates a syntax error where the compiler expects a closing parenthesis ) but instead encounters the end of a line or an unexpected token. This often happens due to:
Let’s analyze your code to identify and fix the issue. The error is likely in one of the sections where parentheses are used, such as function calls, array operations, or object creation. Below, I’ll walk through the code step by step to pinpoint potential issues and provide a corrected version.
The error often occurs in:
box.new, line.new, label.new).array.new, array.push).Let’s examine the key sections of your code where parentheses are heavily used, as these are the most likely sources of the error.
EngulfingInfo Type Definitiontype EngulfingInfo
int id
float rangeHigh
float rangeLow
bool isBullish
box rectangle
line midLine
bool isBroken
label breakoutLabel
type definition doesn’t use parentheses, so it’s unlikely to be the source of the error.getLineStyle FunctiongetLineStyle(styleString) =>
switch styleString
"Solid" => line.style_solid
"Dotted" => line.style_dotted
"Dashed" => line.style_dashed
=> line.style_solid
styleString are properly closed, and the switch statement doesn’t require additional parentheses.request.security Call[htfOpen, htfHigh, htfLow, htfClose, htfTime] = request.security(syminfo.tickerid, targetTimeframe, [open, high, low, close, time], lookahead=barmerge.lookahead_on)
Error on bar 49: 'step' in loop must be greater than zero. at #main():111
The error message 'step' in loop must be greater than zero in Pine Script indicates an issue with a for loop where the step value (the increment or decrement) is either zero or negative when it should be positive, or vice versa. This error is occurring at line 111 of your script, and it’s related to the loop in the "Check Breakouts and Manage Objects" section.
Let’s analyze the problematic loop, understand why the error occurs, and fix it.
The error points to line 111, which corresponds to the following loop in your code:
if engulfingPatterns.size() > 0
for i = engulfingPatterns.size() - 1 to 0 by -1
pattern = engulfingPatterns.get(i)
// ... rest of the loop logic ...
This loop iterates over the engulfingPatterns array in reverse order, starting from the last index (engulfingPatterns.size() - 1) down to 0, with a step of -1 (indicated by by -1).
The error 'step' in loop must be greater than zero occurs because Pine Script expects the step value to be positive when the loop is iterating in a forward direction (i.e., when the start value is less than the end value). However, in your case, the loop is iterating in a reverse direction (from a higher index to a lower index), so the step should be negative (-1), which is correct in your code.
The error message seems contradictory because your step is already -1, which is appropriate for a reverse loop. This suggests that the issue might not be with the step value itself but rather with how Pine Script interprets the loop bounds or step in certain edge cases. Specifically, the error could be triggered if:
engulfingPatterns is empty, causing engulfingPatterns.size() - 1 to evaluate to -1, which might confuse the loop logic.Let’s break down the loop:
engulfingPatterns.size() - 1 (the last index of the array).0 (the first index of the array).-1 (decrementing by 1 to iterate in reverse).make it MTF with 5 tf can be used at once with checkboxes
To enhance your Pine Script indicator to support Multi-Timeframe (MTF) analysis with up to 5 timeframes, each controlled by a checkbox, we need to make several modifications. The goal is to allow the user to enable/disable each timeframe independently and detect engulfing patterns on all selected timeframes simultaneously. Each timeframe will have its own set of patterns, visual elements, and breakouts, with distinct colors for clarity.
Here’s how we’ll approach this:
request.security to fetch OHLC data for each enabled timeframe.Below is the modified Pine Script code implementing these changes.
//@version=6
indicator("Engulfing Pattern Breakout MTF (5 TFs)", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500)
// =================== Inputs ===================
// Group: Pattern Detection
group_pattern = "Pattern Detection Settings"
showEngulfingShape = input.bool(true, "Show Engulfing Markers", group=group_pattern)
// Group: Timeframe Settings
group_tf = "Timeframe Settings"
useTf1 = input.bool(true, "Use Timeframe 1", group=group_tf)
tf1 = input.timeframe("15", "Timeframe 1", group=group_tf)
useTf2 = input.bool(false, "Use Timeframe 2", group=group_tf)
tf2 = input.timeframe("60", "Timeframe 2", group=group_tf)
useTf3 = input.bool(false, "Use Timeframe 3", group=group_tf)
tf3 = input.timeframe("240", "Timeframe 3", group=group_tf)
useTf4 = input.bool(false, "Use Timeframe 4", group=group_tf)
tf4 = input.timeframe("D", "Timeframe 4", group=group_tf)
useTf5 = input.bool(false, "Use Timeframe 5", group=group_tf)
tf5 = input.timeframe("W", "Timeframe 5", group=group_tf)
// Group: Visuals
group_visuals = "Visual Settings"
showRectangle = input.bool(true, "Show Engulfing Range Rectangle", group=group_visuals)
showMidLine = input.bool(true, "Show Range Midpoint Line (POC Proxy)", group=group_visuals)
showBreakoutLabel = input.bool(true, "Show Breakout Labels", group=group_visuals)
// Colors for each timeframe
tf1BullColor = input.color(color.new(color.green, 70), "TF1 Bullish Color", group=group_visuals)
tf1BearColor = input.color(color.new(color.red, 70), "TF1 Bearish Color", group=group_visuals)
tf1MidLineColor = input.color(color.new(color.blue, 50), "TF1 Midpoint Line Color", group=group_visuals)
tf1BreakoutLabelColor = input.color(color.new(color.orange, 0), "TF1 Breakout Label Color", group=group_visuals)
tf2BullColor = input.color(color.new(color.lime, 70), "TF2 Bullish Color", group=group_visuals)
tf2BearColor = input.color(color.new(color.maroon, 70), "TF2 Bearish Color", group=group_visuals)
tf2MidLineColor = input.color(color.new(color.teal, 50), "TF2 Midpoint Line Color", group=group_visuals)
tf2BreakoutLabelColor = input.color(color.new(color.yellow, 0), "TF2 Breakout Label Color", group=group_visuals)
tf3BullColor = input.color(color.new(color.olive, 70), "TF3 Bullish Color", group=group_visuals)
tf3BearColor = input.color(color.new(color.purple, 70), "TF3 Bearish Color", group=group_visuals)
tf3MidLineColor = input.color(color.new(color.navy, 50), "TF3 Midpoint Line Color", group=group_visuals)
tf3BreakoutLabelColor = input.color(color.new(color.white, 0), "TF3 Breakout Label Color", group=group_visuals)
tf4BullColor = input.color(color.new(color.green, 50), "TF4 Bullish Color", group=group_visuals)
tf4BearColor = input.color(color.new(color.red, 50), "TF4 Bearish Color", group=group_visuals)
tf4MidLineColor = input.color(color.new(color.blue, 30), "TF4 Midpoint Line Color", group=group_visuals)
tf4BreakoutLabelColor = input.color(color.new(color.orange, 20), "TF4 Breakout Label Color", group=group_visuals)
tf5BullColor = input.color(color.new(color.lime, 50), "TF5 Bullish Color", group=group_visuals)
tf5BearColor = input.color(color.new(color.maroon, 50), "TF5 Bearish Color", group=group_visuals)
tf5MidLineColor = input.color(color.new(color.teal, 30), "TF5 Midpoint Line Color", group=group_visuals)
tf5BreakoutLabelColor = input.color(color.new(color.yellow, 20), "TF5 Breakout Label Color", group=group_visuals)
midLineStyleOption = input.string("Dashed", "Midpoint Line Style", options=["Solid", "Dotted", "Dashed"], group=group_visuals)
// =================== Data Structure ===================
type EngulfingInfo
int id
int detectedBarIndex
float rangeHigh
float rangeLow
bool isBullish
box rectangle
line midLine
bool isBroken
label breakoutLabel
string timeframe // New field to track which timeframe the pattern belongs to
// =================== Variables ===================
var engulfingPatterns = array.new<EngulfingInfo>()
var int patternIdCounter = 0
getLineStyle(styleString) =>
switch styleString
"Solid" => line.style_solid
"Dotted" => line.style_dotted
"Dashed" => line.style_dashed
=> line.style_solid
midLineStyle = getLineStyle(midLineStyleOption)
// =================== Helper Functions ===================
isBullishEngulfing(o, c, o1, c1) =>
o1 > c1 and c > o and c > o1 and o < c1
isBearishEngulfing(o, c, o1, c1) =>
c1 > o1 and o > c and o > c1 and c < o1
// Function to process patterns for a given timeframe
processTimeframe(tf, useTf, bullColor, bearColor, midLineColor, breakoutLabelColor, tfName) =>
if not useTf
return
// Fetch MTF data
[htfOpen, htfHigh, htfLow, htfClose, htfTime] = request.security(syminfo.tickerid, tf, [open, high, low, close, time], lookahead=barmerge.lookahead_on)
// Skip if data is not available
if na(htfOpen) or na(htfHigh) or na(htfLow) or na(htfClose) or na(htfTime)
return
// Engulfing detection
htfOpen1 = htfOpen[1]
htfClose1 = htfClose[1]
isNewHtfBar = ta.change(htfTime) != 0
bullEngulfingDetected = isNewHtfBar and isBullishEngulfing(htfOpen, htfClose, htfOpen1, htfClose1)
bearEngulfingDetected = isNewHtfBar and isBearishEngulfing(htfOpen, htfClose, htfOpen1, htfClose1)
// Pattern management
if bullEngulfingDetected or bearEngulfingDetected
patternIdCounter += 1
float midPoint = (htfHigh + htfLow) / 2
bool isBull = bullEngulfingDetected
box_ = showRectangle ? box.new(
left=bar_index,
top=htfHigh,
right=bar_index + 1,
bottom=htfLow,
bgcolor=isBull ? bullColor : bearColor,
border_color=na,
extend=extend.right
) : na
line_ = showMidLine ? line.new(
x1=bar_index,
y1=midPoint,
x2=bar_index + 1,
y2=midPoint,
color=midLineColor,
style=midLineStyle,
width=1,
extend=extend.right
) : na
newPattern = EngulfingInfo.new(
id=patternIdCounter,
detectedBarIndex=bar_index,
rangeHigh=htfHigh,
rangeLow=htfLow,
isBullish=isBull,
rectangle=box_,
midLine=line_,
isBroken=false,
breakoutLabel=na,
timeframe=tfName
)
engulfingPatterns.push(newPattern)
// Plot shapes for engulfing patterns
if showEngulfingShape
plotshape(
bullEngulfingDetected,
title=tfName + " Bullish Engulfing",
location=location.belowbar,
color=bullColor,
style=shape.triangleup,
size=size.small
)
plotshape(
bearEngulfingDetected,
title=tfName + " Bearish Engulfing",
location=location.abovebar,
color=bearColor,
style=shape.triangledown,
size=size.small
)
// Function to check breakouts for a given timeframe
checkBreakouts(tf, bullColor, bearColor, midLineColor, breakoutLabelColor, tfName) =>
if engulfingPatterns.size() > 0
for i = 0 to engulfingPatterns.size() - 1
pattern = engulfingPatterns.get(engulfingPatterns.size() - 1 - i)
// Only process patterns for the current timeframe
if pattern.timeframe != tfName
continue
if pattern.isBroken
continue
breakCondition = false
labelText = ""
// Fetch MTF close for breakout detection
htfClose = request.security(syminfo.tickerid, tf, close, lookahead=barmerge.lookahead_on)
if pattern.isBullish and htfClose > pattern.rangeHigh
breakCondition := true
labelText := "▲ " + tfName + " Breakout"
else if not pattern.isBullish and htfClose < pattern.rangeLow
breakCondition := true
labelText := "▼ " + tfName + " Breakout"
if breakCondition
pattern.isBroken := true
if showRectangle and not na(pattern.rectangle)
pattern.rectangle.set_extend(extend.none)
pattern.rectangle.set_right(bar_index)
if showMidLine and not na(pattern.midLine)
pattern.midLine.set_extend(extend.none)
pattern.midLine.set_x2(bar_index)
if showBreakoutLabel
labelY = pattern.isBullish ? pattern.rangeHigh * 1.001 : pattern.rangeLow * 0.999
labelStyle = pattern.isBullish ? label.style_label_down : label.style_label_up
newLabel = label.new(
bar_index,
labelY,
labelText,
color=color.new(color.black, 100),
textcolor=breakoutLabelColor,
style=labelStyle,
size=size.small
)
pattern.breakoutLabel := newLabel
// =================== Main Logic ===================
// Process patterns for each timeframe
processTimeframe(tf1, useTf1, tf1BullColor, tf1BearColor, tf1MidLineColor, tf1BreakoutLabelColor, "TF1")
processTimeframe(tf2, useTf2, tf2BullColor, tf2BearColor, tf2MidLineColor, tf2BreakoutLabelColor, "TF2")
processTimeframe(tf3, useTf3, tf3BullColor, tf3BearColor, tf3MidLineColor, tf3BreakoutLabelColor, "TF3")
processTimeframe(tf4, useTf4, tf4BullColor, tf4BearColor, tf4MidLineColor, tf4BreakoutLabelColor, "TF4")
processTimeframe(tf5, useTf5, tf5BullColor, tf5BearColor, tf5MidLineColor, tf5BreakoutLabelColor, "TF5")
// Check breakouts for each timeframe
checkBreakouts(tf1, tf1BullColor, tf1BearColor, tf1MidLineColor, tf1BreakoutLabelColor, "TF1")
checkBreakouts(tf2, tf2BullColor, tf2BearColor, tf2MidLineColor, tf2BreakoutLabelColor, "TF2")
checkBreakouts(tf3, tf3BullColor, tf3BearColor, tf3MidLineColor, tf3BreakoutLabelColor, "TF3")
checkBreakouts(tf4, tf4BullColor, tf4BearColor, tf4MidLineColor, tf4BreakoutLabelColor, "TF4")
checkBreakouts(tf5, tf5BullColor, tf5BearColor, tf5MidLineColor, tf5BreakoutLabelColor, "TF5")
Patterns are stored in an array (engulfingPatterns) for tracking and management.
request.security to fetch OHLC data from the specified timeframe (htfInput).lookahead=barmerge.lookahead_on ensures accurate historical data fetching.isNewHtfBar).EngulfingInfo object is created and added to the engulfingPatterns array.extend.right) until a breakout occurs.isBroken flag is set to true.extend.none) and are fixed to the current bar.plotshape.EngulfingInfo type and an array to manage patterns is efficient and scalable.Issue: The engulfingPatterns array grows indefinitely as new patterns are detected. This could lead to performance issues on charts with many bars, especially since Pine Script has limits on the number of objects (e.g., max_boxes_count, max_lines_count).
Solution: Implement a cleanup mechanism to remove old patterns that are no longer relevant (e.g., patterns that are broken and far in the past). For example, you could limit the array size or remove patterns older than a certain number of bars.
var int maxPatternsToKeep = 50
if engulfingPatterns.size() > maxPatternsToKeep
oldPattern = engulfingPatterns.shift()
if not na(oldPattern.rectangle)
box.delete(oldPattern.rectangle)
if not na(oldPattern.midLine)
line.delete(oldPattern.midLine)
if not na(oldPattern.breakoutLabel)
label.delete(oldPattern.breakoutLabel)
Issue: The breakout logic only checks the current close (close) against the range high/low. This means breakouts are only detected on the chart's timeframe, not the higher timeframe. This could lead to inconsistencies if the higher timeframe is significantly different from the chart timeframe.
Solution: Use the higher timeframe's close (htfClose) for breakout detection to ensure consistency with the pattern detection timeframe.
if pattern.isBullish and htfClose > pattern.rangeHigh
breakCondition := true
labelText := "▲ Breakout"
else if not pattern.isBullish and htfClose < pattern.rangeLow
breakCondition := true
labelText := "▼ Breakout"
max_boxes_count, max_lines_count, and max_labels_count to 100, but it doesn't enforce these limits programmatically. If more than 100 patterns are detected, older objects may not be deleted, leading to unexpected behavior.request.security to fetch volume data and calculate a more precise POC. This would require additional logic and is more complex, but it could enhance the indicator's accuracy.Issue: The script loops through all patterns on every bar to check for breakouts, which could be inefficient if the engulfingPatterns array grows large.
Solution: Consider only checking patterns that are not yet broken (isBroken == false) to reduce unnecessary iterations. This is already partially implemented, but you could further optimize by maintaining a separate array or filtering the loop.
activePatterns = array.filter(engulfingPatterns, (p) => not p.isBroken)
for pattern in activePatterns
// Breakout logic here
Issue: Breakout labels are placed directly at the range high or low, which might cause overlap with price action or other labels.
Solution: Add an offset to the label's y-position to improve readability. For example:
labelY = pattern.isBullish ? pattern.rangeHigh * 1.001 : pattern.rangeLow * 0.999
Issue: The script assumes that request.security always returns valid data, but in rare cases (e.g., missing data on certain timeframes), it might return na. This could cause errors in the engulfing detection logic.
Solution: Add checks for na values in the OHLC data fetched from request.security.
if na(htfOpen) or na(htfHigh) or na(htfLow) or na(htfClose)
continue
Suggestion: Add an input to control the maximum number of bars to extend the rectangle and midpoint line before a breakout. This would prevent visual clutter on long-ranging markets.
maxExtendBars = input.int(50, "Max Bars to Extend Before Breakout", minval=1, group=group_visuals)
Then, in the breakout logic, check if the pattern has extended too far and stop extending it even if no breakout occurs.
Here’s an example of how you might implement some of the suggestions above, focusing on array cleanup and breakout logic:
// =================== Variables ===================
var engulfingPatterns = array.new<EngulfingInfo>()
var int patternIdCounter = 0
var int maxPatternsToKeep = 50 // Limit the number of patterns
// =================== Cleanup Old Patterns ===================
cleanupOldPatterns() =>
if engulfingPatterns.size() > maxPatternsToKeep
oldPattern = engulfingPatterns.shift()
if not na(oldPattern.rectangle)
box.delete(oldPattern.rectangle)
if not na(oldPattern.midLine)
line.delete(oldPattern.midLine)
if not na(oldPattern.breakoutLabel)
label.delete(oldPattern.breakoutLabel)
// =================== Pattern Management ===================
if bullEngulfingDetected or bearEngulfingDetected
patternIdCounter += 1
float midPoint = (htfHigh + htfLow) / 2
bool isBull = bullEngulfingDetected
box_ = showRectangle ? box.new(
left = bar_index,
top = htfHigh,
right = bar_index + 1,
bottom = htfLow,
bgcolor = isBull ? bullColor : bearColor,
border_color = na,
extend = extend.right
) : na
line_ = showMidLine ? line.new(
x1 = bar_index,
y1 = midPoint,
x2 = bar_index + 1,
y2 = midPoint,
color = midLineColor,
style = midLineStyle,
width = 1,
extend = extend.right
) : na
newPattern = EngulfingInfo.new(
id = patternIdCounter,
detectedBarIndex = bar_index,
rangeHigh = htfHigh,
rangeLow = htfLow,
isBullish = isBull,
rectangle = box_,
midLine = line_,
isBroken = false,
breakoutLabel = na
)
engulfingPatterns.push(newPattern)
cleanupOldPatterns()
// =================== Check Breakouts and Manage Objects ===================
if engulfingPatterns.size() > 0
for i = engulfingPatterns.size() - 1 to 0 by -1
pattern = engulfingPatterns.get(i)
if pattern.isBroken
continue
breakCondition = false
labelText = ""
// Use htfClose for breakout detection
if pattern.isBullish and htfClose > pattern.rangeHigh
breakCondition := true
labelText := "▲ Breakout"
else if not pattern.isBullish and htfClose < pattern.rangeLow
breakCondition := true
labelText := "▼ Breakout"
if breakCondition
pattern.isBroken := true
if showRectangle and not na(pattern.rectangle)
pattern.rectangle.set_extend(extend.none)
pattern.rectangle.set_right(bar_index)
if showMidLine and not na(pattern.midLine)
pattern.midLine.set_extend(extend.none)
pattern.midLine.set_x2(bar_index)
if showBreakoutLabel
labelY = pattern.isBullish ? pattern.rangeHigh * 1.001 : pattern.rangeLow * 0.999
labelStyle = pattern.isBullish ? label.style_label_down : label.style_label_up
newLabel = label.new(bar_index, labelY, labelText,
color = color.new(color.black, 100),
textcolor = breakoutLabelColor,
style = labelStyle,
size = size.small)
pattern.breakoutLabel := newLabel
This is a robust and feature-rich indicator, but it could benefit from the optimizations and enhancements suggested above, especially for performance and user experience. Depending on your goals, you might also consider adding features like:
If you have specific questions or need help implementing any of the suggestions, feel free to ask!
request.security function call has properly balanced parentheses, and the array destructuring on the left side is valid.box.new Call in Pattern Managementbox_ = showRectangle ? box.new(
left = bar_index,
top = htfHigh,
right = bar_index + 1,
bottom = htfLow,
bgcolor = isBull ? bullColor : bearColor,
border_color = na,
extend = extend.right
) : na
box.new arguments are properly closed, and the ternary operator syntax is correct. However, Pine Script is sensitive to line breaks and indentation within function calls. If there’s an extra line break or missing comma, it could cause the error. Let’s ensure the formatting is correct.line.new Call in Pattern Managementline_ = showMidLine ? line.new(
x1 = bar_index,
y1 = midPoint,
x2 = bar_index + 1,
y2 = midPoint,
color = midLineColor,
style = midLineStyle,
width = 1,
extend = extend.right
) : na
box.new call, this section uses a ternary operator and a multi-line function call. The parentheses are properly closed, but again, Pine Script’s strict syntax rules mean that any formatting issues (e.g., missing commas or incorrect indentation) could trigger the error.EngulfingInfo.new CallnewPattern = EngulfingInfo.new(
id = patternIdCounter,
detectedBarIndex = bar_index,
rangeHigh = htfHigh,
rangeLow = htfLow,
isBullish = isBull,
rectangle = box_,
midLine = line_,
isBroken = false,
breakoutLabel = na
)
EngulfingInfo type. The parentheses are properly closed, and the named arguments are correctly formatted. However, if there’s a missing comma or an extra line break, it could cause the error.label.new Call in Breakout LogicnewLabel = label.new(bar_index, labelY, labelText,
color = color.new(color.black, 100),
textcolor = breakoutLabelColor,
style = labelStyle,
size = size.small)
plotshape Callsplotshape(
showEngulfingShape and bullEngulfingDetected,
title = "Bullish Engulfing",
location = location.belowbar,
color = color.green,
style = shape.triangleup,
size = size.small
)
plotshape(
showEngulfingShape and bearEngulfingDetected,
title = "Bearish Engulfing",
location = location.abovebar,
color = color.red,
style = shape.triangledown,
size = size.small
)
plotshape calls have properly balanced parentheses and correct formatting. These are unlikely to be the source of the error.Based on the analysis, the error is most likely caused by one of the following:
box.new, line.new, or label.new, forgetting a comma could trigger the error.To fix the error, we need to ensure that all multi-line function calls have:
Let’s reformat the potentially problematic sections (box.new, line.new, EngulfingInfo.new, and label.new) to ensure correctness.
box.new Callbox_ = showRectangle ? box.new(
left=bar_index,
top=htfHigh,
right=bar_index + 1,
bottom=htfLow,
bgcolor=isBull ? bullColor : bearColor,
border_color=na,
extend=extend.right
) : na
line.new Callline_ = showMidLine ? line.new(
x1=bar_index,
y1=midPoint,
x2=bar_index + 1,
y2=midPoint,
color=midLineColor,
style=midLineStyle,
width=1,
extend=extend.right
) : na
EngulfingInfo.new CallnewPattern = EngulfingInfo.new(
id=patternIdCounter,
detectedBarIndex=bar_index,
rangeHigh=htfHigh,
rangeLow=htfLow,
isBullish=isBull,
rectangle=box_,
midLine=line_,
isBroken=false,
breakoutLabel=na
)
label.new CallnewLabel = label.new(
bar_index,
labelY,
labelText,
color=color.new(color.black, 100),
textcolor=breakoutLabelColor,
style=labelStyle,
size=size.small
)
Below is the full corrected code with proper formatting and syntax. I’ve also added comments to highlight the changes and ensure clarity.
//@version=6
indicator("Engulfing Pattern Breakout MTF", overlay=true, max_boxes_count=100, max_lines_count=100, max_labels_count=100)
// =================== Inputs ===================
// Group: Pattern Detection
group_pattern = "Pattern Detection Settings"
htfInput = input.timeframe("", "Higher Timeframe (Leave empty for chart TF)", group=group_pattern)
showEngulfingShape = input.bool(true, "Show Engulfing Markers", group=group_pattern)
// Group: Visuals
group_visuals = "Visual Settings"
showRectangle = input.bool(true, "Show Engulfing Range Rectangle", group=group_visuals)
showMidLine = input.bool(true, "Show Range Midpoint Line (POC Proxy)", group=group_visuals)
showBreakoutLabel = input.bool(true, "Show Breakout Labels", group=group_visuals)
bullColor = input.color(color.new(color.green, 70), "Bullish Color", group=group_visuals)
bearColor = input.color(color.new(color.red, 70), "Bearish Color", group=group_visuals)
midLineColor = input.color(color.new(color.blue, 50), "Midpoint Line Color", group=group_visuals)
midLineStyleOption = input.string("Dashed", "Midpoint Line Style", options=["Solid", "Dotted", "Dashed"], group=group_visuals)
breakoutLabelColor = input.color(color.new(color.orange, 0), "Breakout Label Color", group=group_visuals)
// =================== Data Structure ===================
type EngulfingInfo
int id
int detectedBarIndex
float rangeHigh
float rangeLow
bool isBullish
box rectangle
line midLine
bool isBroken
label breakoutLabel
// =================== Variables ===================
var engulfingPatterns = array.new<EngulfingInfo>()
var int patternIdCounter = 0
getLineStyle(styleString) =>
switch styleString
"Solid" => line.style_solid
"Dotted" => line.style_dotted
"Dashed" => line.style_dashed
=> line.style_solid
midLineStyle = getLineStyle(midLineStyleOption)
// =================== MTF Data Fetching ===================
useHtf = htfInput != ""
targetTimeframe = useHtf ? htfInput : timeframe.period
[htfOpen, htfHigh, htfLow, htfClose, htfTime] = request.security(syminfo.tickerid, targetTimeframe, [open, high, low, close, time], lookahead=barmerge.lookahead_on)
// =================== Engulfing Detection Logic ===================
isBullishEngulfing(o, c, o1, c1) =>
o1 > c1 and c > o and c > o1 and o < c1
isBearishEngulfing(o, c, o1, c1) =>
c1 > o1 and o > c and o > c1 and c < o1
htfOpen1 = htfOpen[1]
htfClose1 = htfClose[1]
isNewHtfBar = ta.change(htfTime) != 0
bullEngulfingDetected = isNewHtfBar and isBullishEngulfing(htfOpen, htfClose, htfOpen1, htfClose1)
bearEngulfingDetected = isNewHtfBar and isBearishEngulfing(htfOpen, htfClose, htfOpen1, htfClose1)
// =================== Pattern Management ===================
if bullEngulfingDetected or bearEngulfingDetected
patternIdCounter += 1
float midPoint = (htfHigh + htfLow) / 2
bool isBull = bullEngulfingDetected
// Corrected box.new call with consistent indentation and commas
box_ = showRectangle ? box.new(
left=bar_index,
top=htfHigh,
right=bar_index + 1,
bottom=htfLow,
bgcolor=isBull ? bullColor : bearColor,
border_color=na,
extend=extend.right
) : na
// Corrected line.new call with consistent indentation and commas
line_ = showMidLine ? line.new(
x1=bar_index,
y1=midPoint,
x2=bar_index + 1,
y2=midPoint,
color=midLineColor,
style=midLineStyle,
width=1,
extend=extend.right
) : na
// Corrected EngulfingInfo.new call with consistent indentation and commas
newPattern = EngulfingInfo.new(
id=patternIdCounter,
detectedBarIndex=bar_index,
rangeHigh=htfHigh,
rangeLow=htfLow,
isBullish=isBull,
rectangle=box_,
midLine=line_,
isBroken=false,
breakoutLabel=na
)
engulfingPatterns.push(newPattern)
// =================== Check Breakouts and Manage Objects ===================
if engulfingPatterns.size() > 0
for i = engulfingPatterns.size() - 1 to 0 by -1
pattern = engulfingPatterns.get(i)
if pattern.isBroken
continue
breakCondition = false
labelText = ""
if pattern.isBullish and close > pattern.rangeHigh
breakCondition := true
labelText := "▲ Breakout"
else if not pattern.isBullish and close < pattern.rangeLow
breakCondition := true
labelText := "▼ Breakout"
if breakCondition
pattern.isBroken := true
if showRectangle and not na(pattern.rectangle)
pattern.rectangle.set_extend(extend.none)
pattern.rectangle.set_right(bar_index)
if showMidLine and not na(pattern.midLine)
pattern.midLine.set_extend(extend.none)
pattern.midLine.set_x2(bar_index)
if showBreakoutLabel
labelY = pattern.isBullish ? pattern.rangeHigh : pattern.rangeLow
labelStyle = pattern.isBullish ? label.style_label_down : label.style_label_up
// Corrected label.new call with consistent indentation and commas
newLabel = label.new(
bar_index,
labelY,
labelText,
color=color.new(color.black, 100),
textcolor=breakoutLabelColor,
style=labelStyle,
size=size.small
)
pattern.breakoutLabel := newLabel
// =================== Plot Shapes (Fixed) ===================
plotshape(
showEngulfingShape and bullEngulfingDetected,
title="Bullish Engulfing",
location=location.belowbar,
color=color.green,
style=shape.triangleup,
size=size.small
)
plotshape(
showEngulfingShape and bearEngulfingDetected,
title="Bearish Engulfing",
location=location.abovebar,
color=color.red,
style=shape.triangledown,
size=size.small
)
If the error persists, here are some additional steps to debug:
box.new, line.new, or label.new calls) to isolate the problematic line.The error is most likely due to a formatting issue in one of the multi-line function calls (box.new, line.new, EngulfingInfo.new, or label.new). The corrected code above should resolve the issue by ensuring proper syntax, indentation, and commas. If you still encounter problems, please provide the exact line number of the error or share any additional error messages, and I’ll help you further!
This is a standard reverse loop, and it should work correctly as long as engulfingPatterns.size() is greater than 0. The if engulfingPatterns.size() > 0 condition before the loop ensures that the loop only runs if the array is not empty, so the start value should never be -1.
Given that the loop syntax appears correct, the error might be caused by one of the following:
engulfingPatterns.size() is 0, the loop should not execute at all due to the if condition. However, if there’s a bug or race condition in how the array size is evaluated, it might cause the loop to be misinterpreted.To fix the error, we need to ensure that the loop is correctly interpreted by Pine Script. Here are several approaches to resolve the issue:
Instead of using a reverse loop with a negative step, we can iterate forward through the array and calculate the index manually. This avoids the need for a negative step, which might be causing the error.
if engulfingPatterns.size() > 0
for i = 0 to engulfingPatterns.size() - 1
pattern = engulfingPatterns.get(engulfingPatterns.size() - 1 - i)
// ... rest of the loop logic ...
0 to engulfingPatterns.size() - 1) with a default step of 1 (positive, as expected by Pine Script). Inside the loop, we calculate the reverse index (engulfingPatterns.size() - 1 - i) to access the elements in reverse order.To ensure that the loop bounds and step are correctly interpreted, we can add explicit type checking and validation. For example, we can cast the array size to an integer and double-check the step value.
if engulfingPatterns.size() > 0
int arraySize = int(engulfingPatterns.size())
for i = arraySize - 1 to 0 by -1
pattern = engulfingPatterns.get(i)
// ... rest of the loop logic ...
engulfingPatterns.size() is treated as an integer, which might help Pine Script interpret the loop correctly.If the for loop with a negative step is causing issues, we can replace it with a while loop, which gives us more explicit control over the iteration.
if engulfingPatterns.size() > 0
int i = engulfingPatterns.size() - 1
while i >= 0
pattern = engulfingPatterns.get(i)
// ... rest of the loop logic ...
i -= 1
for loop entirely and uses a while loop to iterate in reverse. It’s more verbose but eliminates any potential issues with Pine Script’s for loop syntax.If the above approaches don’t resolve the issue, the error might be due to hidden characters or formatting issues in the code. To test this, manually retype the loop section in the Pine Script editor instead of copying and pasting.
Based on the analysis, the simplest and most reliable fix is Approach 1 (rewriting the loop to avoid reverse iteration). This approach avoids the negative step issue while maintaining the same logic. Below is the corrected code with this fix applied.
//@version=6
indicator("Engulfing Pattern Breakout MTF", overlay=true, max_boxes_count=100, max_lines_count=100, max_labels_count=100)
// =================== Inputs ===================
// Group: Pattern Detection
group_pattern = "Pattern Detection Settings"
htfInput = input.timeframe("", "Higher Timeframe (Leave empty for chart TF)", group=group_pattern)
showEngulfingShape = input.bool(true, "Show Engulfing Markers", group=group_pattern)
// Group: Visuals
group_visuals = "Visual Settings"
showRectangle = input.bool(true, "Show Engulfing Range Rectangle", group=group_visuals)
showMidLine = input.bool(true, "Show Range Midpoint Line (POC Proxy)", group=group_visuals)
showBreakoutLabel = input.bool(true, "Show Breakout Labels", group=group_visuals)
bullColor = input.color(color.new(color.green, 70), "Bullish Color", group=group_visuals)
bearColor = input.color(color.new(color.red, 70), "Bearish Color", group=group_visuals)
midLineColor = input.color(color.new(color.blue, 50), "Midpoint Line Color", group=group_visuals)
midLineStyleOption = input.string("Dashed", "Midpoint Line Style", options=["Solid", "Dotted", "Dashed"], group=group_visuals)
breakoutLabelColor = input.color(color.new(color.orange, 0), "Breakout Label Color", group=group_visuals)
// =================== Data Structure ===================
type EngulfingInfo
int id
int detectedBarIndex
float rangeHigh
float rangeLow
bool isBullish
box rectangle
line midLine
bool isBroken
label breakoutLabel
// =================== Variables ===================
var engulfingPatterns = array.new<EngulfingInfo>()
var int patternIdCounter = 0
getLineStyle(styleString) =>
switch styleString
"Solid" => line.style_solid
"Dotted" => line.style_dotted
"Dashed" => line.style_dashed
=> line.style_solid
midLineStyle = getLineStyle(midLineStyleOption)
// =================== MTF Data Fetching ===================
useHtf = htfInput != ""
targetTimeframe = useHtf ? htfInput : timeframe.period
[htfOpen, htfHigh, htfLow, htfClose, htfTime] = request.security(syminfo.tickerid, targetTimeframe, [open, high, low, close, time], lookahead=barmerge.lookahead_on)
// =================== Engulfing Detection Logic ===================
isBullishEngulfing(o, c, o1, c1) =>
o1 > c1 and c > o and c > o1 and o < c1
isBearishEngulfing(o, c, o1, c1) =>
c1 > o1 and o > c and o > c1 and c < o1
htfOpen1 = htfOpen[1]
htfClose1 = htfClose[1]
isNewHtfBar = ta.change(htfTime) != 0
bullEngulfingDetected = isNewHtfBar and isBullishEngulfing(htfOpen, htfClose, htfOpen1, htfClose1)
bearEngulfingDetected = isNewHtfBar and isBearishEngulfing(htfOpen, htfClose, htfOpen1, htfClose1)
// =================== Pattern Management ===================
if bullEngulfingDetected or bearEngulfingDetected
patternIdCounter += 1
float midPoint = (htfHigh + htfLow) / 2
bool isBull = bullEngulfingDetected
box_ = showRectangle ? box.new(
left=bar_index,
top=htfHigh,
right=bar_index + 1,
bottom=htfLow,
bgcolor=isBull ? bullColor : bearColor,
border_color=na,
extend=extend.right
) : na
line_ = showMidLine ? line.new(
x1=bar_index,
y1=midPoint,
x2=bar_index + 1,
y2=midPoint,
color=midLineColor,
style=midLineStyle,
width=1,
extend=extend.right
) : na
newPattern = EngulfingInfo.new(
id=patternIdCounter,
detectedBarIndex=bar_index,
rangeHigh=htfHigh,
rangeLow=htfLow,
isBullish=isBull,
rectangle=box_,
midLine=line_,
isBroken=false,
breakoutLabel=na
)
engulfingPatterns.push(newPattern)
// =================== Check Breakouts and Manage Objects ===================
if engulfingPatterns.size() > 0
// Fixed loop: Iterate forward and calculate reverse index
for i = 0 to engulfingPatterns.size() - 1
pattern = engulfingPatterns.get(engulfingPatterns.size() - 1 - i)
if pattern.isBroken
continue
breakCondition = false
labelText = ""
if pattern.isBullish and close > pattern.rangeHigh
breakCondition := true
labelText := "▲ Breakout"
else if not pattern.isBullish and close < pattern.rangeLow
breakCondition := true
labelText := "▼ Breakout"
if breakCondition
pattern.isBroken := true
if showRectangle and not na(pattern.rectangle)
pattern.rectangle.set_extend(extend.none)
pattern.rectangle.set_right(bar_index)
if showMidLine and not na(pattern.midLine)
pattern.midLine.set_extend(extend.none)
pattern.midLine.set_x2(bar_index)
if showBreakoutLabel
labelY = pattern.isBullish ? pattern.rangeHigh : pattern.rangeLow
labelStyle = pattern.isBullish ? label.style_label_down : label.style_label_up
newLabel = label.new(
bar_index,
labelY,
labelText,
color=color.new(color.black, 100),
textcolor=breakoutLabelColor,
style=labelStyle,
size=size.small
)
pattern.breakoutLabel := newLabel
// =================== Plot Shapes (Fixed) ===================
plotshape(
showEngulfingShape and bullEngulfingDetected,
title="Bullish Engulfing",
location=location.belowbar,
color=color.green,
style=shape.triangleup,
size=size.small
)
plotshape(
showEngulfingShape and bearEngulfingDetected,
title="Bearish Engulfing",
location=location.abovebar,
color=color.red,
style=shape.triangledown,
size=size.small
)
If the error persists or you encounter other issues, here are some additional steps to debug:
engulfingPatterns to a small number (e.g., 1 or 2) to see if the loop behaves correctly.plotchar) to print the array size and loop indices to verify the loop behavior.The error was likely caused by a quirk in how Pine Script handles reverse loops with negative steps, possibly due to an edge case or a bug in the compiler. By rewriting the loop to iterate forward and calculate the reverse index manually, we avoid the issue while maintaining the same logic. If you encounter further issues or need additional help, please provide the exact error message or describe the behavior, and I’ll assist you further!
tf1 to tf5) with default values (15m, 1h, 4h, daily, weekly).useTf1 to useTf5) to enable/disable each timeframe.EngulfingInfo Typetimeframe field to track which timeframe a pattern belongs to. This allows us to filter patterns during breakout checks.processTimeframe **: This function handles pattern detection and visualization for a given timeframe. It’s called for each timeframe, but only executes if the corresponding checkbox is enabled.checkBreakouts **: This function checks for breakouts on patterns belonging to a specific timeframe. It uses the timeframe’s close price (htfClose) for breakout detection to ensure consistency with the pattern detection timeframe.engulfingPatterns array, but each pattern is tagged with its timeframe (timeframe field). This allows us to filter patterns during breakout checks.htfClose), ensuring consistency with the pattern detection timeframe.max_boxes_count, max_lines_count, and max_labels_count to 500 to accommodate patterns from multiple timeframes. Note that Pine Script has hard limits, so you may need to implement a cleanup mechanism (as suggested in my previous response) if you exceed these limits.Use Timeframe 1 to Use Timeframe 5) to enable/disable each timeframe.W) might result in very few patterns being detected.plotchar) to print intermediate values (e.g., array size, pattern details) to the chart.This modified indicator now supports up to 5 timeframes with independent checkboxes, allowing you to analyze engulfing patterns across multiple timeframes simultaneously. Each timeframe’s patterns are visualized with distinct colors, and breakouts are detected consistently using the respective timeframe’s data. If you need further enhancements (e.g., alerts, filters, or cleanup mechanisms), or if you encounter any issues, please let me know, and I’ll assist you further!