explaine me how liquidity lines work in the script:
//@version=6
indicator('Liquidity Lines & Sweeps + FVG [Lucien] with VWAP', overlay = true, max_lines_count = 500)
// === LIQUIDITY SETTINGS ===
liquidityBool = input.bool(true, 'Show Liquidity Sweeps', group = 'Liquidity Settings')
liquidity_len = input.int(15, 'Liquidity Length', minval = 5, group = 'Liquidity Settings')
upColor = input.color(color.new(color.yellow, 15), title = 'Bullish Liquidity Color', group = 'Liquidity Settings')
downColor = input.color(color.new(color.yellow, 15), title = 'Bearish Liquidity Color', group = 'Liquidity Settings')
i want something similar( just liquidity lines) for metatrader5
Assistant
User
37 error,
Assistant
User
28 errors:
no indicator plot defined for indicator 0 0
'Create' - undeclared identifier liq.mq5 33 21
')' - expression expected liq.mq5 33 28
')' - expression expected liq.mq5 34 28
')' - open parenthesis expected liq.mq5 98 28
')' - open parenthesis expected liq.mq5 113 28
class type expected, pointer to type 'LiquidityLine' is not allowed liq.mq5 127 21
'LiquidityLine' - class type expected liq.mq5 127 28
'At' - object required liq.mq5 127 47
class type expected, pointer to type 'LiquidityLine' is not allowed liq.mq5 142 18
'll' - parameter conversion not allowed liq.mq5 158 12
// --- True range for label positioning ---
tr = ta.tr(true)
// --- Bias Detection for EMA (no chart labels now) ---
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue2)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue2)
// === FVG SETTINGS ===
isFvgToShow = input(true, title='Display FVG', group="Fair Value Gap")
bullishFvgColor = input.color(color.new(color.green, 50), 'Bullish FVG Color', group="Fair Value Gap")
bearishFvgColor = input.color(color.new(color.red, 50), 'Bearish FVG Color', group="Fair Value Gap")
mitigatedFvgColor = input.color(color.new(color.gray, 50), 'Mitigated FVG Color', group="Fair Value Gap")
fvgHistoryNbr = input.int(5, 'Number of FVG to show', minval=1, maxval=50, group="Fair Value Gap")
isMitigatedFvgToReduce = input(false, title='Reduce mitigated FVG', group="Fair Value Gap")
// === DATA STRUCTURES ===
// For Liquidity
type liquidity
float value
int barStart
int barEnd
line liquidityLine
bool broken
label sweep
var array bullishLiquidity = array.new()
var array bearishLiquidity = array.new()
// For FVG
var array fvgBoxes = array.new_box(0)
var array fvgTypes = array.new_bool(0)
var array fvgLabels = array.new_label(0)
var array isFvgMitigated = array.new_bool(0)
// === FVG FUNCTIONS ===
FVGDraw(_boxes, _fvgTypes, _isFvgMitigated, _fvgLabels) =>
for [index, value] in _boxes
// Processing bullish FVG
if array.get(_fvgTypes, index)
if low <= box.get_bottom(value)
array.remove(_boxes, index)
array.remove(_fvgTypes, index)
array.remove(_isFvgMitigated, index)
label.delete(array.get(_fvgLabels, index))
array.remove(_fvgLabels, index)
box.delete(value)
else
if low < box.get_top(value)
box.set_bgcolor(value, mitigatedFvgColor)
if not array.get(_isFvgMitigated, index)
alert("FVG has been mitigated", alert.freq_once_per_bar)
array.set(_isFvgMitigated, index, true)
if isMitigatedFvgToReduce
box.set_top(value, low)
box.set_right(value, bar_index)
label.set_x(array.get(_fvgLabels, index), (box.get_left(value) + box.get_right(value)) / 2 )
label.set_y(array.get(_fvgLabels, index), box.get_top(value) - (box.get_top(value) - box.get_bottom(value)) / 2)
// Processing bearish FVG
else
if high >= box.get_top(value)
array.remove(_boxes, index)
array.remove(_fvgTypes, index)
array.remove(_isFvgMitigated, index)
label.delete(array.get(_fvgLabels, index))
array.remove(_fvgLabels, index)
box.delete(value)
else
if high > box.get_bottom(value)
box.set_bgcolor(value, mitigatedFvgColor)
if not array.get(_isFvgMitigated, index)
alert("FVG has been mitigated", alert.freq_once_per_bar)
array.set(_isFvgMitigated, index, true)
if isMitigatedFvgToReduce
box.set_bottom(value, high)
box.set_right(value, bar_index)
label.set_x(array.get(_fvgLabels, index), (box.get_left(value) + box.get_right(value)) / 2 )
label.set_y(array.get(_fvgLabels, index), box.get_top(value) - (box.get_top(value) - box.get_bottom(value)) / 2)
// === UPDATE VISUALS ===
// Update Liquidity Lines and Sweeps
var bool sweepAlert = false
if array.size(bearishLiquidity) > 0
liquidity testLiquidity = na
for i = array.size(bearishLiquidity) - 1 to 0 by 1
testLiquidity := array.get(bearishLiquidity, i)
if high > testLiquidity.value
testLiquidity.liquidityLine.set_x2(time)
testLiquidity.liquidityLine.set_style(line.style_dashed)
array.remove(bearishLiquidity, i)
if close < testLiquidity.value
testLiquidity.sweep := label.new(x = time, y = high, text = 'x', xloc = xloc.bar_time, style = label.style_label_down, size = size.normal, textcolor = color.new(color.purple, 0), color = color.new(color.white, 100))
sweepAlert := true
else
testLiquidity.liquidityLine.set_x2(time)
if array.size(bullishLiquidity) > 0
liquidity testLiquidity = na
for i = array.size(bullishLiquidity) - 1 to 0 by 1
testLiquidity := array.get(bullishLiquidity, i)
if low < testLiquidity.value
testLiquidity.liquidityLine.set_x2(time)
testLiquidity.liquidityLine.set_style(line.style_dashed)
array.remove(bullishLiquidity, i)
if close > testLiquidity.value
testLiquidity.sweep := label.new(x = time, y = low, text = 'x', xloc = xloc.bar_time, style = label.style_label_up, size = size.normal, textcolor = color.new(color.teal, 0), color = color.new(color.white, 100))
sweepAlert := true
else
testLiquidity.liquidityLine.set_x2(time)
// === ALERTS ===
alertcondition(sweepAlert, title = "Liquidity Sweep", message = "A liquidity zone has been swept.")
sweepAlert := false
// === PREVIOUS DAY HIGH/LOW SETTINGS ===
showPrevDayRange = input.bool(true, 'Show Previous Day High/Low', group='Previous Day Range')
prevDayColorHigh = input.color(color.new(color.red, 0), 'Previous Day High Color', group='Previous Day Range')
prevDayColorLow = input.color(color.new(color.red, 0), 'Previous Day Low Color', group='Previous Day Range')
prevDayLineWidth = input.int(1, 'Previous Day Line Width', minval=1, maxval=5, group='Previous Day Range')
prevDayLineStyle = input.string('Dashed', 'Previous Day Line Style', options=['Dashed', 'Dotted'], group='Previous Day Range')
// Convert line style string to line.style constant
lineStyle = prevDayLineStyle == 'Dotted' ? line.style_dotted : line.style_dashed
// Get previous day timeframe string or use 'D'
dailyTF = "D" // fixed daily timeframe
// Request previous daily data (high/low) and previous day start timestamp (session start)
prevDayHigh = request.security(syminfo.tickerid, dailyTF, high[1], lookahead=barmerge.lookahead_on)
prevDayLow = request.security(syminfo.tickerid, dailyTF, low[1], lookahead=barmerge.lookahead_on)
prevDayTime = request.security(syminfo.tickerid, dailyTF, time[1], lookahead=barmerge.lookahead_on) // Timestamp of previous daily bar start
// Variables to hold lines just once (persistent)
var line prevHighLine = na
var line prevLowLine = na
// Overlays - Range Only
//-----------------------------------------------------------------------------{
if show_sesa
get_range(is_sesa, sesa_txt, sesa_css)
if show_sesb
get_range(is_sesb, sesb_txt, sesb_css)
if show_sesc
get_range(is_sesc, sesc_txt, sesc_css)
if show_sesd
get_range(is_sesd, sesd_txt, sesd_css)
//-----------------------------------------------------------------------------}
// User Inputs for Customization
bullishBreakColor = input.color(color.white, "Bull CISD", inline = "bup")
bearishBreakColor = input.color(color.white, "Bear CISD", inline = "bep")
bullStr = input.string("+CISD", " ", tooltip = "Text to be displayed next to the CISD level.", inline = "bup")
bearStr = input.string("-CISD", " ", tooltip = "Text to be displayed next to the CISD level.", inline = "bep")
bullishAlerts = input.bool(false, "Alert?", "When set up through Tradingview, the script will send an alert when price closes ABOVE the current '+CISD' level.", inline = "bup")
bearishAlerts = input.bool(false, "Alert?", "When set up through Tradingview, the script will send an alert when price closes ABOVE the current '-CISD' level.", inline = "bep")
// Variable Declarations
var line lastTopLine = na
var line lastBottomLine = na
var MarketStructure currentStructure = MarketStructure.new(0, 0, false)
var cisdLevelsBu = array.new()
var cisdLevelsBe = array.new()
var bool isBullishPullback = false
var bool isBearishPullback = false
var float potentialTopPrice = na
var float potentialBottomPrice = na
var int bullishBreakIndex = na
var int bearishBreakIndex = na
var float bullishChangeLevel = na
var float bearishChangeLevel = na
// Bearish Pullback Logic
if bearishPullbackDetected and not isBearishPullback
isBearishPullback := true
potentialTopPrice := open[1]
bullishBreakIndex := bar_index[1]
// Bullish Pullback Logic
if bullishPullbackDetected and not isBullishPullback
isBullishPullback := true
potentialBottomPrice := open[1]
bearishBreakIndex := bar_index[1]
// Update Potential Levels During Pullbacks
if isBullishPullback
if open < potentialBottomPrice
potentialBottomPrice := open
bearishBreakIndex := bar_index
if (close < open) and (open > potentialBottomPrice)
potentialBottomPrice := open
bearishBreakIndex := bar_index
if isBearishPullback
if open > potentialTopPrice
potentialTopPrice := open
bullishBreakIndex := bar_index
if (close > open) and open < potentialTopPrice
potentialTopPrice := open
bullishBreakIndex := bar_index
if array.size(cisdLevelsBu) > 1 and not keepLevels
latest = array.shift(cisdLevelsBu)
line.delete(latest.level)
label.delete(latest.txt)
if array.size(cisdLevelsBe) > 1 and not keepLevels
latest = array.shift(cisdLevelsBe)
line.delete(latest.level)
label.delete(latest.txt)
if array.size(cisdLevelsBu) >= 1
latest = array.get(cisdLevelsBu,0)
if not (close < latest.level.get_y2()) and not latest.completed
line.set_x2(latest.level, bar_index+lookAheadBars)
label.set_x(latest.txt, bar_index+lookAheadBars)
if close < latest.level.get_y2() and not latest.completed
latest.completed := true
alert("Bearish CISD Formed")
if array.size(cisdLevelsBe) >= 1 and not keepLevels
latest = array.get(cisdLevelsBe,0)
if not (close > latest.level.get_y2()) and not latest.completed
line.set_x2(latest.level, bar_index+lookAheadBars)
label.set_x(latest.txt, bar_index+lookAheadBars)
if close > latest.level.get_y2() and not latest.completed
latest.completed := true
alert("Bullish CISD Formed")
// Groups
General_Settings_group = '-------MSS General Settings-------'
Timeframe_1_Group = '-------Timeframe 1 Settings--------'
// Tooltips
Hide_MS_Tooltip = 'If true will hide all MS plots such as "HH 2H" or "HH 15min"'
Hide_Breaks_Tooltip = 'If true will hide all MS breaks such as "BOS 1H" or "MSS 15min"'
Timeframe_Tooltip = 'If set to chart is true no need to alter these two inputs.'
Set_To_Chart_Tooltip = 'If set to chart is set to true, there is no need to alter the Timeframe inputs, it will automatically configure itself to the charts timeframe.'
Lower_Timeframe_Tooltip = 'If set to true and chart timeframe is higher than the choosen timeframe, structure will not display. Note plotting ltf structure on a htf will provide inaccurate plots.'
Use_High_Low_Tooltip = 'If set to true high and low values will be used to confirm market structure else if set to false close will be used.'
Display_TF_Pivots = 'If true the script will display the timeframe declared in the TF inputs'
Display_TF_MS = 'If true the script will display the timeframe's market structure declared in the TF inputs if Hide all Market Structure is false in general settings.'
BOS_Alert_Tooltip = 'Set to true to activate BOS alerts then proceed to set the any alert function specifically on this script.'
MSS_Alert_Tooltip = 'Set to true to activate MSS alerts then proceed to set the any alert function specifically on this script.'
BOS_Plot_Tooltip = 'If set to true the TF BOS plots will be plotted else if false they will be hidden.'
MSS_Plot_Tooltip = 'If set to true the TF MSS plots will be plotted else if false they will be hidden.'
// General Settings
Hide_All_MS = input.bool(defval = true, title = 'Hide all Market Structure', group = General_Settings_group, tooltip = Hide_MS_Tooltip)
Hide_All_Breaks = input.bool(defval = false, title = 'Hide all Structure Breaks', group = General_Settings_group, tooltip = Hide_Breaks_Tooltip)
Show_Only_On_Lower_Timeframes = input.bool(defval = true, title = 'Show Structure only on a lower Timeframe', group = General_Settings_group, tooltip = Lower_Timeframe_Tooltip)
// User Inputs
// Timeframe 1 Settings
TF_1_Use_Bos_Plot = input.bool(defval = false, title = 'Show TF 1 BOS Plots', group = Timeframe_1_Group, tooltip = BOS_Plot_Tooltip)
TF_1_Use_MSS_Plot = input.bool(defval = true, title = 'Show TF 1 MSS Plots', group = Timeframe_1_Group, tooltip = MSS_Plot_Tooltip)
TF_1_Chart_Feature = input.bool(defval = true, title = 'Set Timeframe to Chart', group = Timeframe_1_Group, tooltip = Set_To_Chart_Tooltip)
TF_1_Use_High_Low = input.bool(defval = false, title = 'Use High/Low for Bos & Mss', group = Timeframe_1_Group, tooltip = Use_High_Low_Tooltip)
TF_1_Display_Pivots = input.bool(defval = true, title = 'Display Market Structure', group = Timeframe_1_Group, tooltip = Display_TF_MS)
TF_1_Display_Timeframe = input.bool(defval = true, title = 'Display Timeframe', group = Timeframe_1_Group, tooltip = Display_TF_Pivots)
TF_1_BOS_Alert = input.bool(defval = true, title = 'Use TF 1 BOS Alert', group = Timeframe_1_Group, tooltip = BOS_Alert_Tooltip)
TF_1_MSS_Alert = input.bool(defval = true, title = 'Use TF 1 MSS Alert', group = Timeframe_1_Group, tooltip = MSS_Alert_Tooltip)
TF_1_Multip = input.int(defval = 15, minval = 1, maxval = 1440, title = 'Timeframe 1', group = Timeframe_1_Group, inline = 'T1')
TF_1_Period = input.string(defval = 'Minute', title = '', options = ['Minute', 'Hour', 'Day', 'Week', 'Month'], group = Timeframe_1_Group, inline = 'T1', tooltip = Timeframe_Tooltip)
TF_1_Swing_Length = input.int(defval = 4, title = 'Swing Length', minval = 1, group = Timeframe_1_Group)
TF_1_Line_Type = input.string(defval = 'Solid', title = 'Border Type', options = ['Solid', 'Dashed', 'Dotted'], group = Timeframe_1_Group)
TF_1_Line_Width = input.int(defval = 2, title = 'Line Width', group = Timeframe_1_Group)
TF_1_Text_Size = input.string(defval = 'Small', title = 'Text Size', options = ['Normal', 'Tiny', 'Small', 'Large', 'Huge', 'Auto'], group = Timeframe_1_Group)
TF_1_Bul_Bos_Col = input.color(defval = color.green, title = 'Bullish Bos/Mss Color', group = Timeframe_1_Group, inline = 'TF 1 Color')
TF_1_Bear_Bos_Col = input.color(defval = color.red, title = 'Bearish Bos/Mss Color', group = Timeframe_1_Group, inline = 'TF 1 Color')
TF_1_Bul_MS_Col = input.color(defval = color.white, title = 'Bullish Text MS Color', group = Timeframe_1_Group, inline = 'TF 1 Ms Color')
TF_1_Bear_MS_Col = input.color(defval = color.white, title = 'Bearish Text MS Color', group = Timeframe_1_Group, inline = 'TF 1 Ms Color')
// General functions
// Getting the line type from the user.
Line_Type_Control(Type) =>
Line_Functionality = switch Type
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
Line_Functionality
// Text size from the user
Text_Size_Switch(Text_Size) =>
Text_Type = switch Text_Size
'Normal' => size.normal
'Tiny' => size.tiny
'Small' => size.small
'Large' => size.large
'Huge' => size.huge
'Auto' => size.auto
Text_Type
TF_Period == 'Month' and timeframe.isweekly and 5 / (TF_Multip * 1440 * 5 / timeframe.multiplier) * 1440 == timeframe.multiplier => TF_Multip * 1440 * 5 / 1440 * Swing_Length
TF_Period == 'Month' and timeframe.isdaily and 5 * 5 / (TF_Multip * 1440 * 5 * 5 / timeframe.multiplier) * 1440 == timeframe.multiplier => TF_Multip * 1440 * 5 * 5 / 1440 * Swing_Length
timeframe.ismonthly and timeframe.multiplier == TF_Multip and TF_Period == 'Month' => Swing_Length
TF_Period == 'Week' and timeframe.isminutes and timeframe.multiplier % 60 == 0 and 24 * 5 / (TF_Multip * 1440 * 5 / timeframe.multiplier) * 60 == timeframe.multiplier => TF_Multip * 1440 * 5 / timeframe.multiplier * Swing_Length
TF_Period == 'Week' and timeframe.isdaily and 5 / (TF_Multip * 1440 * 5 / timeframe.multiplier) * 1440 == timeframe.multiplier => TF_Multip * 1440 * 5 / 1440 * Swing_Length
timeframe.isweekly and timeframe.multiplier == TF_Multip and TF_Period == 'Week' => Swing_Length
TF_Period == 'Day' and timeframe.isminutes and timeframe.multiplier % 60 == 0 and 24 / (TF_Multip * 1440 / timeframe.multiplier) * 60 == timeframe.multiplier => TF_Multip * 1440 / timeframe.multiplier * Swing_Length
timeframe.isdaily and timeframe.multiplier == TF_Multip and TF_Period == 'Day' => Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Minute' and TF_Multip == timeframe.multiplier => Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Minute' and TF_Multip != timeframe.multiplier => TF_Multip / 60 * 60 / timeframe.multiplier * Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Hour' and TF_Multip != timeframe.multiplier => TF_Multip * 60 / 60 * 60 / timeframe.multiplier * Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Hour' and TF_Multip == timeframe.multiplier and timeframe.multiplier * 60 == 60 => TF_Multip * 60 / 60 * 60 / timeframe.multiplier * Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Day' and TF_Multip != timeframe.multiplier => TF_Multip * 1440 / 60 * 60 / timeframe.multiplier * Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 == 0 and TF_Period == 'Hour' and TF_Multip * 60 == timeframe.multiplier => Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 == 0 and TF_Period == 'Hour' and TF_Multip * 60 != timeframe.multiplier => TF_Multip * 60 / timeframe.multiplier * Swing_Length
HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip) =>
if Chart_as_Timeframe == true
true
else if Show_Only_On_Lower_Timeframes == false
true
else
switch
TF_Period == 'Minute' and TF_Multip < timeframe.multiplier and timeframe.isminutes => false
TF_Period == 'Minute' and TF_Multip >= timeframe.multiplier and timeframe.isminutes => true
TF_Period == 'Minute' and timeframe.isdaily => false
TF_Period == 'Minute' and timeframe.isweekly => false
TF_Period == 'Minute' and timeframe.ismonthly => false
TF_Period == 'Hour' and TF_Multip * 60 < timeframe.multiplier and timeframe.isminutes => false
TF_Period == 'Hour' and TF_Multip * 60 >= timeframe.multiplier and timeframe.isminutes => true
TF_Period == 'Hour' and timeframe.isdaily => false
TF_Period == 'Hour' and timeframe.isweekly => false
TF_Period == 'Hour' and timeframe.ismonthly => false
TF_Period == 'Day' and timeframe.isdaily or timeframe.isminutes => true
TF_Period == 'Week' and timeframe.isweekly or timeframe.isdaily or timeframe.isminutes => true
TF_Period == 'Month' and timeframe.ismonthly or timeframe.isweekly or timeframe.isdaily or timeframe.isminutes => true
// Calculating the Mtf BOS and MSS
// Getting the high and low values
[TF_1_SH, TF_1_SL] = request.security(symbol = syminfo.tickerid, timeframe = TF_1_Chart_Feature ? timeframe.period : TF(TF_1_Period, TF_1_Multip), expression = [ta.pivothigh(high, TF_1_Swing_Length, TF_1_Swing_Length), ta.pivotlow(low, TF_1_Swing_Length, TF_1_Swing_Length)], gaps = barmerge.gaps_on)
Count_Candles_For_Structure(Direction, Condition) =>
var int High_Count = 0
var int Low_Count = 0
if Direction == 'Bullish'
for i = 0 to Condition by 1
High_Count := i
High_Count
High_Count
else if Direction == 'Bearish'
for i = 0 to Condition by 1
Low_Count := i
Low_Count
Low_Count
Certainly! Let's focus specifically on how liquidity lines work in this Pine Script indicator. I'll explain the concept, how the script detects liquidity lines, tracks them, and marks liquidity sweeps.
What are Liquidity Lines?
In trading, liquidity often refers to price levels where many stop orders or pending orders might reside. These levels often act as magnets for price, where the market can "sweep" these orders before moving towards a new trend.
The indicator identifies such liquidity zones using pivot highs and pivot lows, and then it draws lines at these price levels to denote zones considered liquidity pools.
How Liquidity Lines are Detected in the Script
Step 1: Identify Pivot Highs/Lows as Liquidity Zones
These lines are created where significant pivot highs/lows occur:
ta.pivothigh(high, liquidity_len, liquidity_len) checks if high[liquidity_len] is a pivot high over liquidity_len bars on both sides.
Similarly, ta.pivotlow(low, liquidity_len, liquidity_len) checks for pivot lows.
Therefore, when a pivot high or low is detected (with length defined by liquidity_len input, default 15 bars), that price level is considered a liquidity zone.
Step 2: Store Liquidity Zones in Arrays
If a pivot high is detected and liquidity lines are enabled:
if not na(phLiquidity) and liquidityBool
liquidity newLiquidity = liquidity.new()
newLiquidity.value := high[liquidity_len] // The pivot high value, liquidity price level
newLiquidity.barStart := time[liquidity_len] // Time where liquidity starts
newLiquidity.barEnd := time // Current bar time for end of line
newLiquidity.broken := false // Not broken initially
newLiquidity.liquidityLine := line.new(x1 = newLiquidity.barStart, y1 = newLiquidity.value, x2 = newLiquidity.barEnd, y2 = newLiquidity.value, xloc = xloc.bar_time, color = downColor, width = 1)
array.push(bearishLiquidity, newLiquidity) // Add to bearishLiquidity array
// Limit size of liquidity array (for performance)
if array.size(bearishLiquidity) > 7
deletedLiquidity = array.shift(bearishLiquidity)
deletedLiquidity.liquidityLine.delete()
A new liquidity structure instance is created.
It's pushed into an array bearishLiquidity (pivot highs are bearish liquidity).
A horizontal line is drawn at the liquidity price (value) extending initially from pivot bar to current bar.
It keeps only the last 7 liquidity zones, deleting the oldest for resource management.
Similarly for pivot lows (bullish liquidity):
if not na(plLiquidity) and liquidityBool
liquidity newLiquidity = liquidity.new()
newLiquidity.value := low[liquidity_len]
newLiquidity.barStart := time[liquidity_len]
newLiquidity.barEnd := time
newLiquidity.broken := false
newLiquidity.liquidityLine := line.new(x1 = newLiquidity.barStart, y1 = newLiquidity.value, x2 = newLiquidity.barEnd, y2 = newLiquidity.value, xloc = xloc.bar_time, color = upColor, width = 1)
array.push(bullishLiquidity, newLiquidity)
if array.size(bullishLiquidity) > 7
deletedLiquidity = array.shift(bullishLiquidity)
deletedLiquidity.liquidityLine.delete()
Step 3: Monitoring and Updating Liquidity Lines — Detecting "Sweeps"
The script continuously checks if price has broken above a bearish liquidity line or below a bullish liquidity line, which might indicate a liquidity sweep.
// Bearish Liquidity Lines Check (pivot highs)
if array.size(bearishLiquidity) > 0
liquidity testLiquidity = na
for i = array.size(bearishLiquidity) - 1 to 0 by 1
testLiquidity := array.get(bearishLiquidity, i)
if high > testLiquidity.value
// Price has broken above the liquidity line
testLiquidity.liquidityLine.set_x2(time)
testLiquidity.liquidityLine.set_style(line.style_dashed)
array.remove(bearishLiquidity, i) // Remove the broken liquidity line
if close < testLiquidity.value
// After breaking above, price closed below -> mark a sweep
testLiquidity.sweep := label.new(x = time, y = high, text = 'x', xloc = xloc.bar_time,
style = label.style_label_down, size = size.normal, textcolor = color.new(color.purple, 0), color = color.new(color.white, 100))
sweepAlert := true
else
// If not broken, extend line to current bar time
testLiquidity.liquidityLine.set_x2(time)
Similarly for bullish liquidity lines:
// Bullish Liquidity Lines Check (pivot lows)
if array.size(bullishLiquidity) > 0
liquidity testLiquidity = na
for i = array.size(bullishLiquidity) - 1 to 0 by 1
testLiquidity := array.get(bullishLiquidity, i)
if low < testLiquidity.value
// Price has broken below bullish liquidity line
testLiquidity.liquidityLine.set_x2(time)
testLiquidity.liquidityLine.set_style(line.style_dashed)
array.remove(bullishLiquidity, i)
if close > testLiquidity.value
// Price closed above after breaking below, mark sweep
testLiquidity.sweep := label.new(x = time, y = low, text = 'x', xloc = xloc.bar_time,
style = label.style_label_up, size = size.normal, textcolor = color.new(color.teal, 0), color = color.new(color.white, 100))
sweepAlert := true
else
testLiquidity.liquidityLine.set_x2(time)
Interpretation of Sweeps and Lines
Liquidity Lines (Pivot levels) are plotted as horizontal lines in yellow (default) —
Bearish Liquidity (at pivot highs), colored with downColor
Bullish Liquidity (at pivot lows), colored with upColor
When price breaks through the liquidity level, the line becomes dashed and stops updating (end coordinate fixed to break time).
If price closes back on the opposite side after breaking the liquidity level, it's identified as a "liquidity sweep", and an "x" label is drawn on the chart to mark the sweep.
The sweep condition is useful because it often indicates that market makers or traders "grabbed" stop orders or triggered liquidity before reversing direction.
Alerts
An alert condition triggers when a liquidity zone sweep occurs:
alertcondition(sweepAlert, title = "Liquidity Sweep", message = "A liquidity zone has been swept.")
sweepAlert := false
You can create an alert in TradingView based on this condition.
Summary: How Liquidity Lines Work in This Script
Detect liquidity zones at pivot highs (bearish liquidity) and pivot lows (bullish liquidity).
Draw horizontal lines representing those liquidity zones on the chart.
Track price movement relative to these lines:
If price breaks through a liquidity line, the line becomes dashed, and the liquidity zone is considered "hit."
If price closes back on the other side of the liquidity line after that break, it's marked as a "liquidity sweep" visually with a label.
Limit the number of liquidity lines shown for performance (max 7 for each bullish and bearish).
Trigger alerts when liquidity sweeps occur.
Let me know if you'd like me to explain any particular part of this process or any other section of the script!
Certainly! Below is a simplified example of how you can implement Liquidity Lines with Sweeps logic (similar to the Pine Script you shared) as an MQL5 indicator for MetaTrader 5.
What We’ll Implement:
Detect pivot highs and pivot lows over a lookback period (= liquidity length)
Draw horizontal lines at these pivot levels as liquidity zones
Monitor price breaking these lines, change line styles on break
Mark liquidity sweeps with arrow objects when price breaks and closes back beyond these levels
Important Notes About MQL5:
MQL5 does not have built-in "pivothigh" or "pivotlow" functions exactly like Pine Script, so we'll code basic pivot detection.
Drawing and managing lines and labels is a bit more manual.
We'll use arrays to track liquidity levels, their status, and graphical objects.
MQL5 Indicator Code (Sample)
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots 0
#include <Arrays\ArrayObj.mqh>
// Input parameters
input int LiquidityLength = 15; // lookback length for pivots
input color BullishColor = clrYellow;
input color BearishColor = clrOrangeRed;
input int MaxLiquidityLines = 7;
// Structure to hold liquidity line info
struct LiquidityLine
{
double price;
datetime bar_time_start; // time of pivot bar start
datetime bar_time_end; // last time line extended to
string line_name;
bool broken; // whether liquidity line has been broken
string sweep_arrow_name; // name of graphical object marking sweep - empty if none
};
CArrayObj bullishLiquidity; // Array of LiquidityLine objects for bullish (pivot lows)
CArrayObj bearishLiquidity; // Array of LiquidityLine objects for bearish (pivot highs)
int OnInit()
{
bullishLiquidity.Create();
bearishLiquidity.Create();
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
// Delete all lines & arrows
ClearLiquidityLines();
}
void OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double& price[])
{
if(rates_total < LiquidityLength*2)
return;
datetime time_array[];
CopyTime(_Symbol, _Period, 0, rates_total, time_array);
// Detect pivots for bearish liquidity (pivot highs)
DetectPivotHighs(rates_total, time_array);
// Detect pivots for bullish liquidity (pivot lows)
DetectPivotLows(rates_total, time_array);
// Check liquidity line breaks for bearish
UpdateLiquidityLines(rates_total, time_array, false);
// Check liquidity line breaks for bullish
UpdateLiquidityLines(rates_total, time_array, true);
}
//--- Detect pivot highs
void DetectPivotHighs(const int rates_total, const datetime time_array[])
{
int last_checked = MathMax(0, rates_total - LiquidityLength - 1);
// To avoid repeated detection, only check bars if new bars are available
// We'll check pivot highs for latest bar only for performance
// Pivot high: high[n] is max over (n-LiquidityLength, n+LiquidityLength)
int idx = LiquidityLength;
if(idx + LiquidityLength >= rates_total)
return;
double pivot_high = iHigh(_Symbol, _Period, idx);
bool is_pivot_high = true;
for(int i = idx - LiquidityLength; i <= idx + LiquidityLength; i++)
{
if(i == idx) continue;
if(iHigh(_Symbol, _Period, i) >= pivot_high)
{
is_pivot_high = false;
break;
}
}
if(is_pivot_high)
{
double price = pivot_high;
datetime pivot_time = time_array[idx];
// Avoid duplicates: check if this pivot price/time already in array
if(!IsLiquidityLevelExist(bearishLiquidity, price, pivot_time))
{
AddLiquidityLine(bearishLiquidity, price, pivot_time, false);
}
}
}
//--- Detect pivot lows
void DetectPivotLows(const int rates_total, const datetime time_array[])
{
int idx = LiquidityLength;
if(idx + LiquidityLength >= rates_total)
return;
double pivot_low = iLow(_Symbol, _Period, idx);
bool is_pivot_low = true;
for(int i = idx - LiquidityLength; i <= idx + LiquidityLength; i++)
{
if(i == idx) continue;
if(iLow(_Symbol, _Period, i) <= pivot_low)
{
is_pivot_low = false;
break;
}
}
if(is_pivot_low)
{
double price = pivot_low;
datetime pivot_time = time_array[idx];
if(!IsLiquidityLevelExist(bullishLiquidity, price, pivot_time))
{
AddLiquidityLine(bullishLiquidity, price, pivot_time, true);
}
}
}
//--- Add liquidity line
void AddLiquidityLine(CArrayObj &arr, double price, datetime pivot_time, bool bullish)
{
// Prepare unique line name
string prefix = bullish ? "BullLiquidityLine_" : "BearLiquidityLine_";
string line_name = prefix + IntegerToString(TimeToStruct(pivot_time).day) + "_" + DoubleToString(price, _Digits);
LiquidityLine * ll = new LiquidityLine;
ll.price = price;
ll.bar_time_start = pivot_time;
ll.bar_time_end = TimeCurrent();
ll.line_name = line_name;
ll.broken = false;
ll.sweep_arrow_name = "";
// Draw horizontal line on chart at price level
if(ObjectFind(0, line_name) == -1)
{
ObjectCreate(0, line_name, OBJ_HLINE, 0, 0, price);
ObjectSetInteger(0, line_name, OBJPROP_COLOR, bullish ? BullishColor : BearishColor);
ObjectSetInteger(0, line_name, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, line_name, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, line_name, OBJPROP_BACK, true); // behind candles, optional
}
arr.Add(ll);
// Limit array size
while(arr.Total() > MaxLiquidityLines)
{
LiquidityLine * oldLine = (LiquidityLine*)arr.At(0);
if(ObjectFind(0, oldLine.line_name) != -1)
ObjectDelete(0, oldLine.line_name);
if(oldLine.sweep_arrow_name != "" && ObjectFind(0, oldLine.sweep_arrow_name) != -1)
ObjectDelete(0, oldLine.sweep_arrow_name);
delete oldLine;
arr.Delete(0);
}
}
//--- Check if liquidity level exists (avoid duplicates)
bool IsLiquidityLevelExist(CArrayObj &arr, double price, datetime barTime)
{
for(int i=0; i<arr.Total(); i++)
{
LiquidityLine * ll = (LiquidityLine*)arr.At(i);
if(MathAbs(ll.price - price) < SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE))
{
// Also check if timestamps close to each other? For simplicity only price match here
return true;
}
}
return false;
}
//--- Update liquidity lines: check if price breaks and mark sweeps
void UpdateLiquidityLines(const int rates_total, const datetime time_array[], bool bullish)
{
CArrayObj &arr = bullish ? bullishLiquidity : bearishLiquidity;
// Get current price data
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double closePrice = iClose(_Symbol, _Period, 0);
double high = iHigh(_Symbol, _Period, 0);
double low = iLow(_Symbol, _Period, 0);
datetime currentBarTime = time_array[0];
// Iterate backwards so removal doesn't break indexing
for(int i=arr.Total()-1; i >= 0; i--)
{
LiquidityLine * ll = (LiquidityLine*)arr.At(i);
if(ll.broken) continue;
bool broken = false;
if(bullish)
{
// bullish liquidity = pivot lows
// If price breaks below liquidity price
if(low < ll.price)
{
broken = true;
}
}
else
{
// bearish liquidity = pivot highs
// If price breaks above liquidity price
if(high > ll.price)
{
broken = true;
}
}
if(broken)
{
// Mark the line style to dashed
ObjectSetInteger(0, ll.line_name, OBJPROP_STYLE, STYLE_DOT);
ll.broken = true;
// Mark sweep only if close crossed in opposite direction after break
bool sweep = false;
if(bullish)
{
if(closePrice > ll.price)
sweep = true;
}
else
{
if(closePrice < ll.price)
sweep = true;
}
if(sweep)
{
// Create an arrow label to mark sweep
string arrow_name = "SweepArrow_" + ll.line_name;
double y_pos = bullish ? low : high;
int arrow_code = bullish ? SYMBOL_ARROWDOWN : SYMBOL_ARROWUP;
if(ObjectFind(0, arrow_name) == -1)
{
ObjectCreate(0, arrow_name, OBJ_ARROW, 0, currentBarTime, y_pos);
ObjectSetInteger(0, arrow_name, OBJPROP_COLOR, bullish ? clrTeal : clrPurple);
ObjectSetInteger(0, arrow_name, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, arrow_name, OBJPROP_BACK, false);
ll.sweep_arrow_name = arrow_name;
}
}
// Remove from array (optional: keep or remove broken)
arr.Delete(i);
delete ll;
}
else
{
// Optionally extend line (MQL5 horizontal lines extend infinitely, so no update required)
// Set bar_time_end if you want time-bound lines, but horizontal lines are infinite
}
}
}
//--- Delete all liquidity lines and arrows on deinit
void ClearLiquidityLines()
{
for(int i=0; i<bullishLiquidity.Total(); i++)
{
LiquidityLine * ll = (LiquidityLine*)bullishLiquidity.At(i);
ObjectDelete(0, ll.line_name);
if(ll.sweep_arrow_name != "")
ObjectDelete(0, ll.sweep_arrow_name);
delete ll;
}
bullishLiquidity.Clear();
for(int i=0; i<bearishLiquidity.Total(); i++)
{
LiquidityLine * ll = (LiquidityLine*)bearishLiquidity.At(i);
ObjectDelete(0, ll.line_name);
if(ll.sweep_arrow_name != "")
ObjectDelete(0, ll.sweep_arrow_name);
delete ll;
}
bearishLiquidity.Clear();
}
How to use
Save this as LiquidityLines.mq5 in your Indicators folder.
Compile in MetaEditor.
Attach to any chart.
Configure LiquidityLength parameter to adjust pivot sensitivity.
Explanation of key logic:
Pivot High / Low detection: The script scans for bars within LiquidityLength on each side to identify pivot highs/lows.
Liquidity lines: When a pivot is detected, a horizontal line is drawn at that price level.
Break Detection: On each tick/bar, the indicator checks if price (high or low) has penetrated these liquidity lines.
Line Style: When broken, line style changes from solid to dotted.
Sweeps: If after break price closes back on the reverse side, an arrow is placed which marks a liquidity sweep.
Memory & Object management: Lines and arrows are deleted and cleaned as necessary to avoid clutter and overhead.
Differences and limitations vs Pine Script
Pine Script works bar-by-bar with arrays natively supporting history, MQL5 is tick-based so some latency in detection may occur.
Pine Script can draw boxes and advanced labels more platform-native; in MT5 you'll need custom graphical objects or third-party libraries.
MQL5 horizontal lines are infinite by default (unlike Pine where lines can have start and end bars). To fix line length you'd need more advanced logic with trendlines or objects that track bars.
Integration with more advanced liquidity zone concepts,
Or even automating removal and better UI controls.
Let me know if you'd like me to assist with those or explain how to implement particular features!
Thanks for letting me know! The sample I provided was a conceptual starting point, and indeed MQL5 can be quite picky with syntax and types.
Let's clean up the example with a working minimal MQL5 indicator that detects pivot highs/lows over a lookback length, draws horizontal lines as liquidity zones, detects breaks, changes line styles, and marks sweeps with arrows.
Working MQL5 Indicator for Liquidity Lines with Sweeps
#property copyright "ChatGPT"
#property link ""
#property version "1.00"
#property indicator_chart_window
#include <Arrays\ArrayObj.mqh>
//--- Inputs
input int LiquidityLength = 15; // Pivot length for liquidity detection
input color BullishColor = clrYellow; // Color for bullish liquidity lines
input color BearishColor = clrOrangeRed; // Color for bearish liquidity lines
input int MaxLiquidityLines = 7; // Max liquidity lines tracked
//--- Structure to hold liquidity line info
struct LiquidityLine
{
double price; // Price of liquidity line
datetime pivotTime; // Time of pivot bar
string lineName; // Chart object name for line
bool broken; // Has it been broken
string sweepArrowName; // Sweep arrow name (if any)
};
//--- Arrays for bullish and bearish liquidity lines
CArrayObj bullishLiquidity;
CArrayObj bearishLiquidity;
//+------------------------------------------------------------------+
//| Indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
bullishLiquidity.Create();
bearishLiquidity.Create();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ClearLiquidityLines();
}
//+------------------------------------------------------------------+
//| Main indicator calculation function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[])
{
// Need enough bars
if(rates_total < LiquidityLength*2+1)
return(0);
// Time array for current chart timeframe
datetime times[];
ArraySetAsSeries(times,true);
CopyTime(_Symbol,_Period,0,rates_total,times);
ArraySetAsSeries(times,true);
// Detect pivots on the 'LiquidityLength' bar ago (to have full lookback)
int pivotIndex = LiquidityLength;
// PivotHigh detection
if(IsPivotHigh(pivotIndex))
{
double pivotPrice = iHigh(_Symbol,_Period,pivotIndex);
datetime pivotTime = times[pivotIndex];
if(!LiquidityExists(bearishLiquidity, pivotPrice, pivotTime))
AddLiquidityLine(bearishLiquidity, pivotPrice, pivotTime, false);
}
// PivotLow detection
if(IsPivotLow(pivotIndex))
{
double pivotPrice = iLow(_Symbol,_Period,pivotIndex);
datetime pivotTime = times[pivotIndex];
if(!LiquidityExists(bullishLiquidity, pivotPrice, pivotTime))
AddLiquidityLine(bullishLiquidity, pivotPrice, pivotTime, true);
}
// Update liquidity lines and monitor breaks
UpdateLiquidityLines(bearishLiquidity, false);
UpdateLiquidityLines(bullishLiquidity, true);
return(rates_total);
}
//+------------------------------------------------------------------+
//| Check if bar at index is a pivot high |
//+------------------------------------------------------------------+
bool IsPivotHigh(int index)
{
double pivot = iHigh(_Symbol,_Period,index);
for(int i = index - LiquidityLength; i <= index + LiquidityLength; i++)
{
if(i == index) continue;
if(i < 0 || i >= Bars) continue; // Safety
if(iHigh(_Symbol,_Period,i) >= pivot)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check if bar at index is a pivot low |
//+------------------------------------------------------------------+
bool IsPivotLow(int index)
{
double pivot = iLow(_Symbol,_Period,index);
for(int i = index - LiquidityLength; i <= index + LiquidityLength; i++)
{
if(i == index) continue;
if(i < 0 || i >= Bars) continue; // Safety
if(iLow(_Symbol,_Period,i) <= pivot)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check if liquidity line already exists |
//+------------------------------------------------------------------+
bool LiquidityExists(CArrayObj &arr, double price, datetime pivotTime)
{
for(int i=0; i<arr.Total(); i++)
{
LiquidityLine *ll = (LiquidityLine*)arr.At(i);
if(MathAbs(ll.price - price) < SymbolInfoDouble(_Symbol,SYMBOL_POINT) && ll.pivotTime == pivotTime)
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| Add liquidity line and draw on chart |
//+------------------------------------------------------------------+
void AddLiquidityLine(CArrayObj &arr, double price, datetime pivotTime, bool bullish)
{
// Generate unique name for line
string lineName = (bullish ? "BullLiquidityLine_" : "BearLiquidityLine_") + IntegerToString(pivotTime) + DoubleToString(price,_Digits);
// Create struct and set values
LiquidityLine *ll = new LiquidityLine();
ll.price = price;
ll.pivotTime = pivotTime;
ll.lineName = lineName;
ll.broken = false;
ll.sweepArrowName = "";
// Draw horizontal line (OBJ_HLINE is infinite)
if(ObjectFind(0,lineName) == -1)
{
ObjectCreate(0,lineName,OBJ_HLINE,0,0,price);
ObjectSetInteger(0,lineName,OBJPROP_COLOR,bullish ? BullishColor : BearishColor);
ObjectSetInteger(0,lineName,OBJPROP_WIDTH,1);
ObjectSetInteger(0,lineName,OBJPROP_STYLE,STYLE_SOLID);
ObjectSetInteger(0,lineName,OBJPROP_BACK,true);
}
arr.Add(ll);
// Maintain max size
while(arr.Total() > MaxLiquidityLines)
{
LiquidityLine *old = (LiquidityLine*)arr.At(0);
ObjectDelete(0,old.lineName);
if(old.sweepArrowName != "") ObjectDelete(0,old.sweepArrowName);
delete old;
arr.Delete(0);
}
}
//+------------------------------------------------------------------+
//| Update liquidity lines, detect breaks and mark sweeps |
//+------------------------------------------------------------------+
void UpdateLiquidityLines(CArrayObj &arr, bool bullish)
{
// Current price data
double closePrice = iClose(_Symbol,_Period,0);
double highPrice = iHigh(_Symbol,_Period,0);
double lowPrice = iLow(_Symbol,_Period,0);
datetime currentTime = TimeCurrent();
for(int i=arr.Total()-1; i>=0; i--)
{
LiquidityLine *ll = (LiquidityLine*)arr.At(i);
if(ll.broken) continue;
bool broken = false;
if(bullish)
{
// For bullish liquidity, break if price low < liquidity line price
if(lowPrice < ll.price)
broken = true;
}
else
{
// For bearish liquidity, break if price high > liquidity line price
if(highPrice > ll.price)
broken = true;
}
if(broken)
{
// Change line to dotted
ObjectSetInteger(0,ll.lineName,OBJPROP_STYLE,STYLE_DOT);
ll.broken = true;
// Check if close price crossed opposite side for sweep
bool sweep = false;
if(bullish && closePrice > ll.price)
sweep = true;
else if(!bullish && closePrice < ll.price)
sweep = true;
if(sweep)
{
// Add arrow marking sweep
string arrowName = "SweepArrow_" + ll.lineName;
if(ObjectFind(0,arrowName) == -1)
{
double y = bullish ? lowPrice : highPrice;
ObjectCreate(0,arrowName,OBJ_ARROW,0,currentTime,y);
ObjectSetInteger(0,arrowName,OBJPROP_COLOR,bullish ? clrTeal : clrPurple);
ObjectSetInteger(0,arrowName,OBJPROP_WIDTH,2);
ObjectSetInteger(0,arrowName,OBJPROP_BACK,false);
ll.sweepArrowName = arrowName;
}
}
// Remove liquidity line from array and free memory
arr.Delete(i);
delete ll;
}
}
}
//+------------------------------------------------------------------+
//| Delete all liquidity lines and sweep arrows on deinit |
//+------------------------------------------------------------------+
void ClearLiquidityLines()
{
for(int i=0; i<bullishLiquidity.Total(); i++)
{
LiquidityLine *ll = (LiquidityLine*)bullishLiquidity.At(i);
ObjectDelete(0,ll.lineName);
if(ll.sweepArrowName != "") ObjectDelete(0,ll.sweepArrowName);
delete ll;
}
bullishLiquidity.Clear();
for(int i=0; i<bearishLiquidity.Total(); i++)
{
LiquidityLine *ll = (LiquidityLine*)bearishLiquidity.At(i);
ObjectDelete(0,ll.lineName);
if(ll.sweepArrowName != "") ObjectDelete(0,ll.sweepArrowName);
delete ll;
}
bearishLiquidity.Clear();
}
How to compile and use
Save as LiquidityLines.mq5
Compile in MetaEditor without errors
Load on any chart. Set your pivot length.
Watch horizontal lines appear at pivot highs/lows.
When price breaks these levels, lines turn dotted.
If price then closes back on opposite side, an arrow marks the sweep.
Key points
Pivot detection: Looks LiquidityLength bars back and forward to find pivot high/low.
Liquidity lines: Represented as infinite horizontal lines (OBJ_HLINE).
Break detection: Detects when price breaks liquidity lines (high > for bearish, low < for bullish).
Sweeps: Marks arrows when price closes opposite side after break.
Line management: Limits max stored liquidity lines & frees graphical objects.
This version should compile cleanly in MetaEditor 5 with no errors.
If you still encounter errors or want enhancements (like fixed-length lines or alerts), let me know!
Thanks for the detailed error report! The main cause of these errors is that MQL5 is strictly typed and does not support struct pointers or classes the same way as Pine Script or other languages. Also, CArrayObj expects array of objects derived from CObject, which structs are not.
So:
We cannot use structs with pointers in CArrayObj.
We need to create a class derived from CObject to hold liquidity line data.
Some functions like Create() don’t exist on CArrayObj—we just declare it.
ArraySetAsSeries() should be called once and correctly.
We must handle CopyTime() and time series carefully.
Here is a corrected, simplified, runnable MQL5 indicator that implements similar liquidity lines with sweeps.
Complete working Liquidity Lines indicator for MT5:
#property copyright "ChatGPT"
#property link ""
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 0
#include <Arrays\ArrayObj.mqh>
//--- Input parameters
input int LiquidityLength = 15; // Pivot length for liquidity detection
input color BullishColor = clrYellow; // Color for bullish liquidity lines
input color BearishColor = clrOrangeRed; // Color for bearish liquidity lines
input int MaxLiquidityLines = 7; // Max liquidity lines tracked
//--- LiquidityLine class
class LiquidityLine : public CObject
{
public:
double price; // Price of liquidity line
datetime pivotTime; // Time of pivot bar
string lineName; // Chart object name for line
bool broken; // Has it been broken
string sweepArrowName; // Sweep arrow name (if any)
// Constructor
void LiquidityLine_Init(double p_price, datetime p_time, string p_name)
{
price = p_price;
pivotTime = p_time;
lineName = p_name;
broken = false;
sweepArrowName = "";
}
};
//--- Arrays for bullish and bearish liquidity lines
CArrayObj bullishLiquidity;
CArrayObj bearishLiquidity;
//+------------------------------------------------------------------+
//| Indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
bullishLiquidity.Clear();
bearishLiquidity.Clear();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ClearLiquidityLines();
}
//+------------------------------------------------------------------+
//| Main indicator calculation function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[])
{
if(rates_total < LiquidityLength * 2 + 1)
return(0);
// Time array for current chart timeframe
datetime times[];
ArraySetAsSeries(times, true);
if(CopyTime(_Symbol, _Period, 0, rates_total, times) <= 0)
return(prev_calculated);
// Detect pivot at bar LiquidityLength (lookback for full pivot)
int pivotIndex = LiquidityLength;
// Detect pivot highs (bearish liquidity)
if(IsPivotHigh(pivotIndex))
{
double pivotPrice = iHigh(_Symbol, _Period, pivotIndex);
datetime pivotTime = times[pivotIndex];
if(!LiquidityExists(bearishLiquidity, pivotPrice, pivotTime))
AddLiquidityLine(bearishLiquidity, pivotPrice, pivotTime, false);
}
// Detect pivot lows (bullish liquidity)
if(IsPivotLow(pivotIndex))
{
double pivotPrice = iLow(_Symbol, _Period, pivotIndex);
datetime pivotTime = times[pivotIndex];
if(!LiquidityExists(bullishLiquidity, pivotPrice, pivotTime))
AddLiquidityLine(bullishLiquidity, pivotPrice, pivotTime, true);
}
// Update liquidity lines and monitor breaks
UpdateLiquidityLines(bearishLiquidity, false);
UpdateLiquidityLines(bullishLiquidity, true);
return(rates_total);
}
//+------------------------------------------------------------------+
//| Check if bar at index is a pivot high |
//+------------------------------------------------------------------+
bool IsPivotHigh(int index)
{
double pivot = iHigh(_Symbol, _Period, index);
int bars = Bars(_Symbol, _Period);
for(int i = index - LiquidityLength; i <= index + LiquidityLength; i++)
{
if(i == index)
continue;
if(i < 0 || i >= bars)
continue;
if(iHigh(_Symbol, _Period, i) >= pivot)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check if bar at index is a pivot low |
//+------------------------------------------------------------------+
bool IsPivotLow(int index)
{
double pivot = iLow(_Symbol, _Period, index);
int bars = Bars(_Symbol, _Period);
for(int i = index - LiquidityLength; i <= index + LiquidityLength; i++)
{
if(i == index)
continue;
if(i < 0 || i >= bars)
continue;
if(iLow(_Symbol, _Period, i) <= pivot)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check if liquidity line already exists |
//+------------------------------------------------------------------+
bool LiquidityExists(CArrayObj &arr, double price, datetime pivotTime)
{
for(int i = 0; i < arr.Total(); i++)
{
LiquidityLine *ll = (LiquidityLine*)arr.At(i);
if(MathAbs(ll.price - price) < SymbolInfoDouble(_Symbol, SYMBOL_POINT) && ll.pivotTime == pivotTime)
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| Add liquidity line and draw on chart |
//+------------------------------------------------------------------+
void AddLiquidityLine(CArrayObj &arr, double price, datetime pivotTime, bool bullish)
{
string lineName = (bullish ? "BullLiquidityLine_" : "BearLiquidityLine_") + IntegerToString(pivotTime) + DoubleToString(price, _Digits);
// Create new LiquidityLine object
LiquidityLine *ll = new LiquidityLine();
ll.LiquidityLine_Init(price, pivotTime, lineName);
// Draw horizontal line on chart
if(ObjectFind(0, lineName) == -1)
{
ObjectCreate(0, lineName, OBJ_HLINE, 0, 0, price);
ObjectSetInteger(0, lineName, OBJPROP_COLOR, bullish ? BullishColor : BearishColor);
ObjectSetInteger(0, lineName, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, lineName, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, lineName, OBJPROP_BACK, true);
}
arr.Add(ll);
// Maintain max size
while(arr.Total() > MaxLiquidityLines)
{
LiquidityLine *old = (LiquidityLine*)arr.At(0);
ObjectDelete(0, old.lineName);
if(old.sweepArrowName != "")
ObjectDelete(0, old.sweepArrowName);
delete old;
arr.Delete(0);
}
}
//+------------------------------------------------------------------+
//| Update liquidity lines, detect breaks and mark sweeps |
//+------------------------------------------------------------------+
void UpdateLiquidityLines(CArrayObj &arr, bool bullish)
{
double closePrice = iClose(_Symbol, _Period, 0);
double highPrice = iHigh(_Symbol, _Period, 0);
double lowPrice = iLow(_Symbol, _Period, 0);
datetime currentTime = TimeCurrent();
for(int i = arr.Total() - 1; i >= 0; i--)
{
LiquidityLine *ll = (LiquidityLine*)arr.At(i);
if(ll.broken) continue;
bool broken = false;
if(bullish)
{
if(lowPrice < ll.price)
broken = true;
}
else
{
if(highPrice > ll.price)
broken = true;
}
if(broken)
{
ObjectSetInteger(0, ll.lineName, OBJPROP_STYLE, STYLE_DOT);
ll.broken = true;
bool sweep = false;
if(bullish && closePrice > ll.price)
sweep = true;
else if(!bullish && closePrice < ll.price)
sweep = true;
if(sweep)
{
string arrowName = "SweepArrow_" + ll.lineName;
if(ObjectFind(0, arrowName) == -1)
{
double y = bullish ? lowPrice : highPrice;
ObjectCreate(0, arrowName, OBJ_ARROW, 0, currentTime, y);
ObjectSetInteger(0, arrowName, OBJPROP_COLOR, bullish ? clrTeal : clrPurple);
ObjectSetInteger(0, arrowName, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, arrowName, OBJPROP_BACK, false);
ll.sweepArrowName = arrowName;
}
}
arr.Delete(i);
delete ll;
}
}
}
//+------------------------------------------------------------------+
//| Delete all liquidity lines and arrows on deinit |
//+------------------------------------------------------------------+
void ClearLiquidityLines()
{
for(int i = 0; i < bullishLiquidity.Total(); i++)
{
LiquidityLine *ll = (LiquidityLine*)bullishLiquidity.At(i);
ObjectDelete(0, ll.lineName);
if(ll.sweepArrowName != "")
ObjectDelete(0, ll.sweepArrowName);
delete ll;
}
bullishLiquidity.Clear();
for(int i = 0; i < bearishLiquidity.Total(); i++)
{
LiquidityLine *ll = (LiquidityLine*)bearishLiquidity.At(i);
ObjectDelete(0, ll.lineName);
if(ll.sweepArrowName != "")
ObjectDelete(0, ll.sweepArrowName);
delete ll;
}
bearishLiquidity.Clear();
}
How to use:
Copy-paste the above code into a new .mq5 file in your Indicators folder (eg. LiquidityLines.mq5).
Compile in MetaEditor. It should produce no errors.
Attach the indicator to any chart.
Adjust LiquidityLength to set the pivot length.
It will draw yellow horizontal lines on pivot lows and orange-red lines on pivot highs.
When price breaks these levels, the line style changes to dotted.
If price then closes back on the opposite side, it places an arrow marking the liquidity sweep.
Explanation of fixes:
Defined LiquidityLine as a class derived from CObject for compatibility with CArrayObj.
Properly initialized LiquidityLine with a separate method LiquidityLine_Init.
Removed "Create()" calls on CArrayObj; arrays are declared and auto-initialized.
Fixed array indexing and pointer casting.
Used CopyTime correctly and set series correctly.
Added safety checks for bar indices.
Used ObjectFind and ObjectCreate properly.
Managed object deletion with delete for dynamic objects.
If you want me to also add alert functionality or fixed-length lines or better UX feel free to ask.
This corrected indicator code should compile and run properly in MT5 without errors.
Let me know if you still face any issues!
Thanks for the update! If the script compiles but shows no lines on chart, it usually means:
Pivot detection isn't firing (because pivots are rare or LiquidityLength is too large).
Or the horizontal lines are there but not visible (color or timeframe issues).
Or the bars calculated for pivot are too early and you can’t see them on newer bars.
How to debug & fix:
1) Reduce LiquidityLength for testing to a small number like 5
Try input:
input int LiquidityLength = 5;
The smaller the value, the easier it is to detect pivots.
2) Add Print statements to check pivot detection
Insert some debugging prints in OnCalculate, for example after detection:
Open Experts or Journal tab and check if these messages appear.
If not, pivot detection is failing — likely due to LiquidityLength or chart data.
3) Check if lines are drawn
Also in AddLiquidityLine(), right after ObjectCreate:
bool created = ObjectCreate(0,lineName,OBJ_HLINE,0,0,price);
if(created)
Print("Liquidity line created for price: ", DoubleToString(price,_Digits));
else
Print("Failed to create line: ", lineName);
If you see "Liquidity line created..." messages but can't see the lines, check the line color, thickness, and chart zoom or timeframe.
4) Change colors for visibility
Some chart backgrounds/colors can make yellow or orange lines hard to see.
Try setting colors to something very visible, e.g.,
input color BullishColor = clrLime; // bright green
input color BearishColor = clrRed; // bright red
5) Verify timeframe and bar indexing logic
This script detects pivots on the bar at index = LiquidityLength in history (not the current bar).
Ensure chart has enough bars loaded (e.g., > LiquidityLength*2 + 1).
Summary: minimal debug version snippet to add in OnCalculate