//--- inputs
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_H1; // Timeframe to look back on
input int InpLookbackCandles = 10; // Base number of candles (>=1)
input double InpMultiplier = 7.0; // Max multiplier (integer part used, >=1)
input bool IncludeCurrentCandle = false; // Include current forming candle in calculations
input double MinimalDistancePoints = 20; // Minimal distance between lines, in points
// Optional color inputs
input color ColorHighLines = clrRed;
input color ColorLowLines = clrBlue;
// Draw lines immediately once on init
UpdateLines();
Print("MultiLookbackLines EA initialized");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ClearLines();
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Get time of the latest completed bar on the input timeframe
datetime currentBarTime = iTime(_Symbol, InpTimeframe, 0);
if(currentBarTime == lastBarTime)
return; // no new bar yet on InpTimeframe
lastBarTime = currentBarTime;
UpdateLines();
}
//+------------------------------------------------------------------+
//| Core function to draw or update all lines with filtering |
//+------------------------------------------------------------------+
void UpdateLines()
{
int maxMult = (int)MathFloor(multiplier);
if(maxMult < 1)
maxMult = 1;
int startPos = IncludeCurrentCandle ? 0 : 1;
//--- Load existing High lines ---
double filteredHighsPrices[];
int filteredHighsMultipliers[];
Assistant
User
make it an mt5 indicator, and do all the updates and fixes
Assistant
User
no indicator plot defined for indicator 0 0
'MinimalDistancePoints' - constant cannot be modified Liquidity Lines.mq5 51 7
'ColorHighLines' - undeclared identifier Liquidity Lines.mq5 55 4
'ColorLowLines' - undeclared identifier Liquidity Lines.mq5 56 4
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
//+------------------------------------------------------------------+
//| Clear lines with defined prefixes |
//+------------------------------------------------------------------+
void ClearLines()
{
int total = ObjectsTotal(0);
for(int i=total-1; i>=0; i--)
{
string name = ObjectName(0, i);
if(StringFind(name, PREFIX_HIGH) == 0 || StringFind(name, PREFIX_LOW) == 0)
ObjectDelete(0, name);
}
}
//+------------------------------------------------------------------+
Your MultiLookbackLines.mq5 code is quite comprehensive. It attempts to draw multiple horizontal lines for local highs and lows using varying lookback periods scaled by a multiplier, filtering lines close to each other by a minimum distance in points.
Summary of what this code does:
Takes an input timeframe, a base lookback candles, and a multiplier to calculate several lookback intervals.
For each multiplier (1 to floor multiplier):
Copies InpLookbackCandles * m bars of rates.
Scans for local highs (high > preceding and next high) and local lows (low < preceding and next low).
Selects the highest local high and lowest local low in this range.
Maintains horizontal lines on chart named with prefixes and the multiplier number.
Avoids drawing lines too close (MinimalDistancePoints).
Deletes outdated lines when multiplier exceeds current max.
Updates lines when a new bar arrives on the chosen timeframe.
Code Review and Suggestions:
The provided script looks logically complete and mostly correct, but here are some points you might want to review or improve:
1. OnTick Bar Time Checking:
mql5
datetime currentBarTime = iTime(_Symbol, InpTimeframe, 0);
if(currentBarTime == lastBarTime)
return; // no new bar yet on InpTimeframe
lastBarTime = currentBarTime;
This is a good approach to process only on new bar.
However, if IncludeCurrentCandle == true, you may want to take care that the "current" candle is used properly. The code already does this with startPos = IncludeCurrentCandle ? 0 : 1;.
2. Local High/Low Detection:
You detect local highs/lows as strictly greater/less than both neighbors:
This is fine but ignores plateaus or equal highs/lows.
Possibly consider >= or <= if you want to catch flat tops/bottoms.
You may want to handle the case when copied < 3, since i=1 to copied-2 loops. If copied is 2 or less, no iteration happens.
3. Array Handling & Line Filtering:
You maintain arrays to hold existing line prices and their multiplier indices for both highs and lows.
When you find a new local high or low, you look for any existing line within MinimalDistancePoints.
If close line exists but the new line is "better" (higher high or lower low), replace existing line.
This logic is sound, but be cautious if multiplied lines can cross over each other in price.
The use of / _Point is correct for converting price difference to points.
4. Object Naming and Parsing:
mql5
int mult_index = (int)StringToInteger(StringSubstr(name, StringLen(PREFIX_HIGH)));
Assumes the multiplier is integer and everything after prefix is multiplier.
Works fine but could add error handling or check for numeric suffix.
5. DrawOrUpdateLine:
Uses OBJ_HLINE with style DOT, width 2, back true.
Nice visual style.
Lines are set non-selectable and deselected; users can't drag them which is intentional.
6. Performance:
Every new bar triggers UpdateLines() which copies rates for multiples of input bars.
For large multipliers or large InpLookbackCandles, it can be costly.
Consider caching rates or optimizing frequency of calls.
Alternatively, you can run logic only when chart timeframe matches your input timeframe or on timer rather than every tick.
7. Minor Improvements:
You may want to add comment blocks inside the UpdateLines function explaining each major step.
Could add input for line width/style.
You might want to handle the case where MinimalDistancePoints is zero or negative (currently no validation).
Add color transparency (alpha channel) or input for line opacity.
Possibly implement alerts or notifications when new significant local highs/lows occur.
Potential issues or bugs to be aware of:
CopyRates() failing to copy enough bars or returning less than requested: your code handles this by skipping.
When the number of bars copied is less than 3, your local high/low loop won’t run (since it loops i=1 to copied-2), resulting in "No valid local high found".
When deleting obsolete lines (mult_index > maxMult), the script deletes lines, but if the multiplier suddenly becomes smaller (say from user input), you might have some lag or not all lines cleaned up immediately.
You might want to handle the case when InpMultiplier is a non-integer >1 (e.g., 7.5) — the code floors it, so it works as intended, but user might expect behavior based on fractional parts.
Overall, this expert advisor (EA) looks solid for drawing multiple lookback based local extremum horizontal lines with filtering for proximity. If you want me to add features or fix a particular bug, or optimize the code further, feel free to ask.
If you want me to check or generate a version for MT4 or convert it to an indicator instead of an EA, or explain a specific part, just ask!
Certainly! Below is a revised, fully MT5 indicator version of your MultiLookbackLines script, incorporating the fixes, improvements, and adjustments requested:
Converted from EA to Indicator.
Uses OnCalculate for updating lines on every new bar of the selected timeframe.
Added checks for minimal copied bars.
Added input validation.
Proper comments added.
Handles fractional multiplier by using floor.
Includes minimal distance validation.
Lines are updated only when a new bar appears on the chosen timeframe.
Made arrays cleaner and more efficient.
Added alpha transparency to colors with input.
mql5
//+------------------------------------------------------------------+
//| MultiLookbackLines.mq5 |
//| Converted from EA by ChatGPT 2024 |
//+------------------------------------------------------------------+
#property copyright "ChatGPT"
#property link ""
#property version "2.00"
#property indicator_chart_window
#property indicator_buffers 0
#property strict
//--- inputs
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_H1; // Timeframe to look back on
input int InpLookbackCandles = 10; // Base number of candles (>=1)
input double InpMultiplier = 7.0; // Max multiplier (integer part used, >=1)
input bool IncludeCurrentCandle = false; // Include current forming candle in calculations
input double MinimalDistancePoints = 20; // Minimal distance between lines, in points (>=0)
input color ColorHighLines_Base = clrRed; // Base color for high lines
input color ColorLowLines_Base = clrBlue; // Base color for low lines
input uint LineAlpha = 150; // Transparency 0-255 (0=fully transparent, 255=no transparency)
//--- defines for naming
#define PREFIX_HIGH "MultiHL_High_"
#define PREFIX_LOW "MultiHL_Low_"
//+------------------------------------------------------------------+
//| Global variables |
//+------------------------------------------------------------------+
datetime lastBarTime = 0; // last processed bar time on input timeframe
//+------------------------------------------------------------------+
//| Indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Input validation
if(InpLookbackCandles < 1)
{
Print("Error: InpLookbackCandles must be >= 1");
return(INIT_FAILED);
}
if(InpMultiplier < 1.0)
{
Print("Warning: InpMultiplier < 1, setting to 1");
}
if(MinimalDistancePoints < 0)
{
Print("Warning: MinimalDistancePoints < 0, setting to 0");
MinimalDistancePoints = 0;
}
// Convert input colors to include alpha transparency
ColorHighLines = ColorModifyAlpha(ColorHighLines_Base, LineAlpha);
ColorLowLines = ColorModifyAlpha(ColorLowLines_Base, LineAlpha);
// Clean existing lines on chart from previous runs
ClearLines();
// Draw initial lines immediately
UpdateLines();
Print("MultiLookbackLines indicator initialized");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Clear lines when indicator is removed
ClearLines();
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double& price[])
{
// We only update when new bar on InpTimeframe
datetime currentBarTime = iTime(_Symbol, InpTimeframe, 0);
if(currentBarTime == lastBarTime)
return(prev_calculated);
lastBarTime = currentBarTime;
UpdateLines();
return(rates_total);
}
//+------------------------------------------------------------------+
//| Core function to calculate and manage horizontal lines |
//+------------------------------------------------------------------+
void UpdateLines()
{
int maxMult = (int)MathFloor(InpMultiplier);
if(maxMult < 1)
maxMult = 1;
int startPos = IncludeCurrentCandle ? 0 : 1;
// Arrays for currently drawn lines and their multiplier
double filteredHighsPrices[];
int filteredHighsMultipliers[];
double filteredLowsPrices[];
int filteredLowsMultipliers[];
// Load existing high/low line objects on chart
int totalObjects = ObjectsTotal(0);
for(int i=totalObjects-1; i>=0; i--)
{
string objName = ObjectName(0, i);
// Process High lines
if(StringFind(objName, PREFIX_HIGH) == 0)
{
double price = ObjectGetDouble(0, objName, OBJPROP_PRICE);
string suffix = StringSubstr(objName, StringLen(PREFIX_HIGH));
int mult_index = (int)StringToInteger(suffix);
if(mult_index <= 0)
continue;
// Delete lines with multiplier exceeding maxMult
if(mult_index > maxMult)
{
ObjectDelete(0, objName);
continue;
}
// Store existing line data for filtering
ArrayResize(filteredHighsPrices, ArraySize(filteredHighsPrices) + 1);
ArrayResize(filteredHighsMultipliers, ArraySize(filteredHighsMultipliers) + 1);
filteredHighsPrices[ArraySize(filteredHighsPrices) - 1] = price;
filteredHighsMultipliers[ArraySize(filteredHighsMultipliers) - 1] = mult_index;
}
// Process Low lines
else if(StringFind(objName, PREFIX_LOW) == 0)
{
double price = ObjectGetDouble(0, objName, OBJPROP_PRICE);
string suffix = StringSubstr(objName, StringLen(PREFIX_LOW));
int mult_index = (int)StringToInteger(suffix);
if(mult_index <= 0)
continue;
if(mult_index > maxMult)
{
ObjectDelete(0, objName);
continue;
}
ArrayResize(filteredLowsPrices, ArraySize(filteredLowsPrices) + 1);
ArrayResize(filteredLowsMultipliers, ArraySize(filteredLowsMultipliers) + 1);
filteredLowsPrices[ArraySize(filteredLowsPrices) - 1] = price;
filteredLowsMultipliers[ArraySize(filteredLowsMultipliers) - 1] = mult_index;
}
}
// Loop through each multiplier to find local highs/lows and update lines
for(int m = 1; m <= maxMult; m++)
{
int barsToLookBack = InpLookbackCandles * m;
MqlRates rates[];
int copied = CopyRates(_Symbol, InpTimeframe, startPos, barsToLookBack, rates);
if(copied < 3)
{
// Not enough bars to find local high/low patterns
PrintFormat("Not enough bars copied (%d) for lookback %d (Multiplier %d)", copied, barsToLookBack, m);
ObjectDelete(0, PREFIX_HIGH + IntegerToString(m));
ObjectDelete(0, PREFIX_LOW + IntegerToString(m));
continue;
}
// Find highest local high and lowest local low in the copied range
double highestLocalHigh = -DBL_MAX;
int highestLocalHighIndex = -1;
double lowestLocalLow = DBL_MAX;
int lowestLocalLowIndex = -1;
for(int i = 1; i < copied - 1; i++)
{
// Local high condition: strictly higher than neighbors
if(rates[i].high > rates[i - 1].high && rates[i].high > rates[i + 1].high)
{
if(rates[i].high > highestLocalHigh)
{
highestLocalHigh = rates[i].high;
highestLocalHighIndex = i;
}
}
// Local low condition: strictly lower than neighbors
if(rates[i].low < rates[i - 1].low && rates[i].low < rates[i + 1].low)
{
if(rates[i].low < lowestLocalLow)
{
lowestLocalLow = rates[i].low;
lowestLocalLowIndex = i;
}
}
}
string highLineName = PREFIX_HIGH + IntegerToString(m);
string lowLineName = PREFIX_LOW + IntegerToString(m);
// -----------------------------------
// Process High line for this multiplier
// -----------------------------------
if(highestLocalHigh == -DBL_MAX)
{
// No valid local high found - delete line if exists
PrintFormat("No valid local high found for multiplier %d (bars %d)", m, barsToLookBack);
ObjectDelete(0, highLineName);
}
else
{
double highest = highestLocalHigh;
// Check for existing close lines to filter by minimal distance
bool highCloseFound = false;
int highCloseIndex = -1;
for(int i = 0; i < ArraySize(filteredHighsPrices); i++)
{
double distPoints = MathAbs(highest - filteredHighsPrices[i]) / _Point;
if(distPoints < MinimalDistancePoints)
{
highCloseFound = true;
highCloseIndex = i;
break;
}
}
if(!highCloseFound)
{
// Add new line data and draw
ArrayResize(filteredHighsPrices, ArraySize(filteredHighsPrices) + 1);
ArrayResize(filteredHighsMultipliers, ArraySize(filteredHighsMultipliers) + 1);
filteredHighsPrices[ArraySize(filteredHighsPrices) - 1] = highest;
filteredHighsMultipliers[ArraySize(filteredHighsMultipliers) - 1] = m;
DrawOrUpdateLine(highLineName, highest, ColorHighLines);
PrintFormat("High line Multiplier %d (%d bars): Local High=%.5f - Drawn", m, barsToLookBack, highest);
}
else
{
// If new high is higher, replace existing line
if(highest > filteredHighsPrices[highCloseIndex])
{
filteredHighsPrices[highCloseIndex] = highest;
int replacedMultiplier = filteredHighsMultipliers[highCloseIndex];
string replacedLineName = PREFIX_HIGH + IntegerToString(replacedMultiplier);
DrawOrUpdateLine(replacedLineName, highest, ColorHighLines);
PrintFormat("High line Multiplier %d replaced with higher local high=%.5f", replacedMultiplier, highest);
}
else
{
// Keep existing line, redraw if missing
if(ObjectFind(0, highLineName) == -1)
DrawOrUpdateLine(highLineName, filteredHighsPrices[highCloseIndex], ColorHighLines);
PrintFormat("High line Multiplier %d skipped due to proximity or lower local high (Local High=%.5f)", m, highest);
}
}
}
// -----------------------------------
// Process Low line for this multiplier
// -----------------------------------
if(lowestLocalLow == DBL_MAX)
{
// No valid local low found - delete line if exists
PrintFormat("No valid local low found for multiplier %d (bars %d)", m, barsToLookBack);
ObjectDelete(0, lowLineName);
}
else
{
double lowest = lowestLocalLow;
// Check for existing close lines to filter by minimal distance
bool lowCloseFound = false;
int lowCloseIndex = -1;
for(int i = 0; i < ArraySize(filteredLowsPrices); i++)
{
double distPoints = MathAbs(lowest - filteredLowsPrices[i]) / _Point;
if(distPoints < MinimalDistancePoints)
{
lowCloseFound = true;
lowCloseIndex = i;
break;
}
}
if(!lowCloseFound)
{
ArrayResize(filteredLowsPrices, ArraySize(filteredLowsPrices) + 1);
ArrayResize(filteredLowsMultipliers, ArraySize(filteredLowsMultipliers) + 1);
filteredLowsPrices[ArraySize(filteredLowsPrices) - 1] = lowest;
filteredLowsMultipliers[ArraySize(filteredLowsMultipliers) - 1] = m;
DrawOrUpdateLine(lowLineName, lowest, ColorLowLines);
PrintFormat("Low line Multiplier %d (%d bars): Local Low=%.5f - Drawn", m, barsToLookBack, lowest);
}
else
{
// If new low is lower, replace existing line
if(lowest < filteredLowsPrices[lowCloseIndex])
{
filteredLowsPrices[lowCloseIndex] = lowest;
int replacedMultiplier = filteredLowsMultipliers[lowCloseIndex];
string replacedLineName = PREFIX_LOW + IntegerToString(replacedMultiplier);
DrawOrUpdateLine(replacedLineName, lowest, ColorLowLines);
PrintFormat("Low line Multiplier %d replaced with lower local low=%.5f", replacedMultiplier, lowest);
}
else
{
// Keep existing line, redraw if missing
if(ObjectFind(0, lowLineName) == -1)
DrawOrUpdateLine(lowLineName, filteredLowsPrices[lowCloseIndex], ColorLowLines);
PrintFormat("Low line Multiplier %d skipped due to proximity or higher local low (Local Low=%.5f)", m, lowest);
}
}
}
}
}
//+------------------------------------------------------------------+
//| Draw or update horizontal line |
//+------------------------------------------------------------------+
void DrawOrUpdateLine(string name, double price, color clr)
{
if(ObjectFind(0, name) == -1)
{
if(!ObjectCreate(0, name, OBJ_HLINE, 0, 0, price))
{
Print("Failed to create line: " + name);
return;
}
ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
ObjectSetInteger(0, name, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT);
ObjectSetInteger(0, name, OBJPROP_BACK, true);
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, name, OBJPROP_SELECTED, false);
}
else
{
ObjectSetDouble(0, name, OBJPROP_PRICE, price);
}
}
//+------------------------------------------------------------------+
//| Clear lines with prefixes |
//+------------------------------------------------------------------+
void ClearLines()
{
int total = ObjectsTotal(0);
for(int i = total - 1; i >= 0; i--)
{
string name = ObjectName(0, i);
if(StringFind(name, PREFIX_HIGH) == 0 || StringFind(name, PREFIX_LOW) == 0)
ObjectDelete(0, name);
}
}
//+------------------------------------------------------------------+
//| Modify the alpha transparency of a color |
//+------------------------------------------------------------------+
color ColorModifyAlpha(color c, uchar alpha)
{
// Unpack input color
uchar r = (uchar)ColorGetR(c);
uchar g = (uchar)ColorGetG(c);
uchar b = (uchar)ColorGetB(c);
// Compose color with new alpha channel
return(ColorMake(r, g, b, alpha));
}
//+------------------------------------------------------------------+
How to use:
Save this script as MultiLookbackLines.mq5 in the Indicators folder (MQL5/Indicators).
Compile it in MetaEditor.
Attach it to any chart.
Use inputs to configure timeframe, base candles, multiplier, minimal distance, colors, transparency, and inclusion of current candle.
Lines will update automatically on every new bar on the chosen timeframe.
Explanation of changes:
The indicator now respects MetaTrader's indicator calculation model.
Draws and updates horizontal lines representing multi-level local highs/lows based on lookback multipliers.
Filters lines that are closer than minimal distance in points.
Uses color transparency input for nicer visuals.
Avoids multiple recalculations on every tick by updating only once per new bar on the chosen timeframe.
Validates inputs and ensures safe use of arrays.
The code is cleaner and contains detailed comments for easier maintenance and understanding.
If you want me to extend this indicator with additional features (alerts, labels, user interaction) or convert it back to EA with the improvements, just ask!
Thanks for pointing out the issues! Those errors are due to:
No indicator plots defined warning: MT5 requires that if you specify #property indicator_buffers X, you either define buffers or remove that line. Since your indicator only creates graphical objects (lines), it should have no buffers defined at all.
‘constant cannot be modified’ error: You declared MinimalDistancePoints as input (input double MinimalDistancePoints = 20;) but then tried to assign it inside OnInit(). Inputs are constants and cannot be modified. You need to copy it to a working variable if you want to modify.
Undeclared variables ColorHighLines and ColorLowLines: Those variables were supposed to hold the alpha-modified colors, but were never declared as globals.
Fixed code snippet (relevant parts):
mql5
//--- inputs
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_H1; // Timeframe to look back on
input int InpLookbackCandles = 10; // Base number of candles (>=1)
input double InpMultiplier = 7.0; // Max multiplier (integer part used, >=1)
input bool IncludeCurrentCandle = false; // Include current forming candle in calculations
input double InpMinimalDistancePoints = 20; // Minimal distance between lines, in points (>=0)
input color ColorHighLines_Base = clrRed; // Base color for high lines
input color ColorLowLines_Base = clrBlue; // Base color for low lines
input uint LineAlpha = 150; // Transparency 0-255 (0=fully transparent, 255=no transparency)
//--- globals for working variables
double MinimalDistancePoints = 20.0; // working copy of minimal distance; can be modified at runtime
color ColorHighLines; // will contain base color with alpha applied
color ColorLowLines; // same for lows
And in OnInit():
mql5
int OnInit()
{
// Input validation and assign inputs to globals that can be modified
if(InpLookbackCandles < 1)
{
Print("Error: InpLookbackCandles must be >= 1");
return(INIT_FAILED);
}
if(InpMultiplier < 1.0)
{
Print("Warning: InpMultiplier < 1, setting to 1");
}
if(InpMinimalDistancePoints < 0)
{
Print("Warning: MinimalDistancePoints < 0, setting to 0");
MinimalDistancePoints = 0;
}
else
MinimalDistancePoints = InpMinimalDistancePoints;
// Convert input colors to colors with alpha transparency
ColorHighLines = ColorModifyAlpha(ColorHighLines_Base, (uchar)LineAlpha);
ColorLowLines = ColorModifyAlpha(ColorLowLines_Base, (uchar)LineAlpha);
ClearLines();
UpdateLines();
Print("MultiLookbackLines indicator initialized");
return(INIT_SUCCEEDED);
}
Also, remove the line:
mql5
#property indicator_buffers 0
since you are not using indicator buffers.
FULL corrected code with fixes incorporated:
mql5
Summary of fixes:
Removed indicator_buffers 0, unnecessary for graphical objects.
Introduced working copy MinimalDistancePoints so input is constant, variable modifiable.
Declared ColorHighLines and ColorLowLines globally and set in OnInit().
Converted LineAlpha (input uint) to uchar and used in color constructor.
Cleaned and restructured code to avoid reassignment of inputs.
Try this code — it should compile without errors and work correctly as an MT5 indicator that draws the multiple lookback horizontal lines!
If you want me to help further with polishing or adding new features, just ask.