i need an mql5 ea, trading trading swing liquidity swap and reversal
Assistant
Creating an MQL5 Expert Advisor (EA) that trades based on swing points, liquidity swaps, and reversals is a complex task that involves defining precise rules for:
Swing trading – Identifying swing highs and lows.
Liquidity swaps – Generally refers to price action concepts where liquidity (stop orders, pending orders) is grabbed or swapped.
Reversal detection – Recognizing when price reverses direction, possibly validated by certain indicators or candle patterns.
What I’ll provide:
A basic MQL5 EA skeleton implementing:
Identification of swing highs/lows.
Detection of a simple liquidity swap concept (e.g., price breaking previous swing high/low and pulling back).
A simple reversal concept using a Moving Average and RSI indicator confirmation.
You will still need to customize and optimize it based on your exact definition and optimization preferences.
Important:
Liquidity swaps is a somewhat ambiguous term without strict algorithmic definition. A common approach is looking for a 'breakout-and-fakeout' or a test of previous liquidity zones.
The EA will trade swing points and try to capture reversals at liquidity areas.
You should backtest and optimize it before live use.
Here is a basic MQL5 Expert Advisor prototype:
mql5
//+------------------------------------------------------------------+
//| SwingLiquidityEA |
//| Basic prototype for swing, liquidity swaps, reversal |
//+------------------------------------------------------------------+
#property copyright "ChatGPT"
#property version "1.00"
#property strict
input double Lots = 0.1;
input int SwingLookback = 5; // Bars to look back for swing highs/lows
input double StopLossPoints = 100; // Stop loss in points
input double TakeProfitPoints=200; // Take profit in points
input int MA_Period = 21; // Moving Average period
input int RSI_Period = 14; // RSI period
input double RSI_Overbought = 70.0;
input double RSI_Oversold = 30.0;
// Globals
bool order_opened = false;
ulong ticket = 0;
//+------------------------------------------------------------------+
//| Check swing high at index |
//+------------------------------------------------------------------+
bool IsSwingHigh(int index, int left, int right)
{
double currentHigh = High[index];
for(int i = index - left; i < index; i++)
{
if(High[i] >= currentHigh)
return false;
}
for(int i = index + 1; i <= index + right; i++)
{
if(High[i] > currentHigh)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check swing low at index |
//+------------------------------------------------------------------+
bool IsSwingLow(int index, int left, int right)
{
double currentLow = Low[index];
for(int i = index - left; i < index; i++)
{
if(Low[i] <= currentLow)
return false;
}
for(int i = index + 1; i <= index + right; i++)
{
if(Low[i] < currentLow)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check for liquidity swap (simple breakout and retest of swing) |
//+------------------------------------------------------------------+
bool LiquiditySwapBuy(int index)
{
// Check price broke above previous swing high (liquidity taken)
// and then retested it with RSI support
// Find previous swing high to compare
int lookback = 20;
double swingHigh = 0.0;
int swingIndex = -1;
for(int i=index - 1; i > index - lookback; i--)
{
if(i<=SwingLookback || i >= Bars - 1)
break;
if(IsSwingHigh(i,SwingLookback,SwingLookback))
{
swingHigh = High[i];
swingIndex = i;
break;
}
}
if(swingHigh == 0.0)
return false;
double currentLow = Low[index];
double currentClose = Close[index];
// Check if price retested swing high area and did not break below much
if(currentLow < swingHigh && currentClose > swingHigh)
{
double rsi = iRSI(_Symbol,_Period,RSI_Period,PRICE_CLOSE,index);
if(rsi > RSI_Oversold && rsi < RSI_Overbought)
return true;
}
return false;
}
bool LiquiditySwapSell(int index)
{
// Analogous for sell, liquidity taken below previous swing low then retest
int lookback = 20;
double swingLow = 0.0;
int swingIndex = -1;
for(int i=index - 1; i > index - lookback; i--)
{
if(i<=SwingLookback || i >= Bars - 1)
break;
if(IsSwingLow(i,SwingLookback,SwingLookback))
{
swingLow = Low[i];
swingIndex = i;
break;
}
}
if(swingLow == 0.0)
return false;
double currentHigh = High[index];
double currentClose = Close[index];
if(currentHigh > swingLow && currentClose < swingLow)
{
double rsi = iRSI(_Symbol,_Period,RSI_Period,PRICE_CLOSE,index);
if(rsi > RSI_Oversold && rsi < RSI_Overbought)
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| Open Buy Order |
//+------------------------------------------------------------------+
bool OpenBuy()
{
MqlTradeRequest request;
MqlTradeResult result;
double price = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = Lots;
request.type = ORDER_TYPE_BUY;
request.price = price;
request.deviation = 10;
request.magic = 123456;
request.sl = price - StopLossPoints * _Point;
request.tp = price + TakeProfitPoints * _Point;
if(!OrderSend(request,result))
{
Print("Buy order send failed: ",result.comment);
return false;
}
ticket = result.order;
order_opened = true;
Print("Buy order opened at ", price);
return true;
}
//+------------------------------------------------------------------+
//| Open Sell Order |
//+------------------------------------------------------------------+
bool OpenSell()
{
MqlTradeRequest request;
MqlTradeResult result;
double price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = Lots;
request.type = ORDER_TYPE_SELL;
request.price = price;
request.deviation = 10;
request.magic = 123456;
request.sl = price + StopLossPoints * _Point;
request.tp = price - TakeProfitPoints * _Point;
if(!OrderSend(request,result))
{
Print("Sell order send failed: ",result.comment);
return false;
}
ticket = result.order;
order_opened = true;
Print("Sell order opened at ", price);
return true;
}
//+------------------------------------------------------------------+
//| On Tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check for existing positions for this EA on this symbol
if(PositionSelect(_Symbol))
{
// Position exists - do nothing or manage trades here
return;
}
// Use the last fully closed bar
int index = 1; // index=1 means last closed bar
// Simple trend filter MA
double ma = iMA(_Symbol,_Period,MA_Period,0,MODE_SMA,PRICE_CLOSE,index);
double close_price = Close[index];
if(close_price > ma)
{
// Consider buy entries only
if(LiquiditySwapBuy(index))
{
OpenBuy();
}
}
else if(close_price < ma)
{
// Consider sell entries only
if(LiquiditySwapSell(index))
{
OpenSell();
}
}
}
//+------------------------------------------------------------------+
Explanation:
Swing highs/lows: Function checks if High or Low of a bar is higher/lower than surrounding bars.
Liquidity swap: Simplified concept where price breaks a previous swing (high for buy, low for sell) and then re-tests it.
Reversal / confirmation: Uses RSI to filter and Moving Average for trend direction.
Order management: Only open one position at a time per symbol.
How to improve:
Add more precise liquidity zone detection (order blocks, S/R zones, etc).
Add better reversal signal filters (e.g., candlestick patterns, volume).
Manage multiple open trades, trailing stops.
Add risk management, break-even, partial closes.
Optimize input parameters and add comments.
If you'd like, I can also help you extend or customize this further. Let me know!
User
i want to see the liquidity zones on chart, white horizontal ray extend to right until price touch it
Assistant
Got it! You want liquidity zones plotted on the chart as white horizontal rays extending to the right — and these rays stop extending once the price touches (or crosses) the zone.
Liquidity zones in the context of swing trading usually refer to key swing highs (resistance zones) and swing lows (support zones) that were formed previously and represent areas where liquidity (pending orders or stops) might be resting.
How this will work:
When a swing high or swing low is detected (using the same logic as your EA),
Draw a horizontal ray at that price level,
The ray will extend to the right indefinitely,
But when price touches the zone, the ray will stop extending (we delete or shorten it).
MQL5 code snippet to show this functionality inside an indicator or combined in the EA
I will write a simple indicator example to focus on liquidity zone visualization because separating drawing and trading logic is cleaner.
MQL5 Indicator: Liquidity Zones Visualization
mql5
User
prefer to keep it and just stop extending
Assistant
Understood — you want the liquidity zones drawn as horizontal rays extending to the right, and when price touches the zone, the ray stops extending further but the horizontal line remains visible (just no longer grows).
How to implement a horizontal ray that stops extending after price touches it?
Unfortunately, the OBJ_HLINE with OBJPROP_RAY_RIGHT cannot be dynamically shortened — it either extends infinitely to the right or doesn't.
The solution is:
At first, draw a horizontal ray (OBJ_HLINE with OBJPROP_RAY_RIGHT=true).
When price touches the zone (crosses the level),
Delete the ray,
Draw a horizontal line (OBJ_HLINE with OBJPROP_RAY_RIGHT=false) fixed at the price level.
This way, initially the zone is a ray extending infinitely to the right, then once price touches it, the ray disappears and a fixed horizontal line remains at that level.
Updated MQL5 indicator code snippet demonstrating this behavior:
The errors “'High' - undeclared identifier” and “‘[’ - array required” happen because High[], Low[], Time[] and other price arrays are only available in indicator/event handler functions with appropriate parameters, or you need to explicitly declare them.
In your script, these arrays like High[] and Low[] are used directly in OnCalculate, but you need to use those arrays passed as parameters or call CopyHigh(), CopyLow(), etc. Alternatively, you can use the High[], Low[], and Time[]series predefined arrays by specifying #property indicator_chart_window and compiling as an indicator.
How to fix these errors:
Use the predefined series arrays High[], Low[], Time[] directly only in indicators or scripts with #property indicator_chart_window and with OnCalculate() as their main entry.
Inside OnCalculate, you must declare appropriate arrays as arguments or use the predefined ones.
Since your code is using High[index] etc. directly, you must declare #property indicator_chart_window and define OnCalculate.
Minimal working example for indicator using High[], Low[] and Time[]
Below is the full minimal skeleton indicator implementing the liquidity zone code that you can compile and run:
The errors you get mean the built-in price arrays (High[], Low[], Time[]) aren't recognized in your code context.
This usually happens if:
You aren't compiling the code as an indicator, or
You're using them inside a script or EA without properly defining or copying the rates.
How to fix this in your context:
1. Are you compiling an indicator or an EA?
The code I gave you with OnCalculate and using High[], Low[], Time[] directly only works inside an indicator.
Indicators have access to series arrays like High[], Low[], Time[] directly.
EAs or scripts do not have direct access to those arrays — you must explicitly request data via CopyHigh(), CopyLow(), CopyTime(), etc.
2. If you want this to work inside an indicator
Make sure:
You saved your code in the /MQL5/Indicators/ folder.
The file has #property indicator_chart_window
It has a valid OnCalculate function as entry point.
If your file is compiled as an .mq5Expert Advisor or Script, these arrays are not predefined — you need to get data from market manually with Copy... functions.
3. If you want to use inside an EA
You must:
Use CopyHigh(), CopyLow(), CopyTime() to copy the price/time data to local arrays.
Then use those arrays instead of direct High[] or Time[].
Here's a minimal example of copying bars data in EA style:
mql5
User
i need an ea
Assistant
Understood! You need an MQL5 Expert Advisor that:
Detects liquidity zones (based on swing highs and lows),
Draws horizontal lines or rays on the chart,
The rays extend to the right and stop extending (converted to fixed horizontal lines) once price touches the zone,
Incorporates this visualization inside the EA itself,
And manages trading separately.
Important notes for EA:
Since EAs don’t have direct access to High[], Low[] arrays, we must use CopyHigh(), CopyLow(), and CopyTime() to get market data.
Drawing objects inside an EA is OK, but be sure to manage objects carefully (create/delete/update as needed).
Run the liquidity zone detection once per new bar.
Complete example EA implementing liquidity zone detection & drawing with ray-to-line behavior
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots 0
input int SwingLookback = 5; // Swing lookback bars
input color LiquidityColor = White;
struct LiquidityZone
{
datetime time; // the bar time where zone created (for delete logic)
double price; // level of liquidity zone
int type; // 1=Swing High (resistance), -1=Swing Low (support)
long obj_id; // Object ID of ray
bool active; // active/valid or price already touched it
};
#define MAX_ZONES 50
LiquidityZone zones[MAX_ZONES];
int zones_count = 0;
//+------------------------------------------------------------------+
//| Check swing high position |
//+------------------------------------------------------------------+
bool IsSwingHigh(int index, int left, int right)
{
double currentHigh = High[index];
for(int i = index - left; i < index; i++)
if(High[i] >= currentHigh)
return false;
for(int i = index + 1; i <= index + right; i++)
if(High[i] > currentHigh)
return false;
return true;
}
//+------------------------------------------------------------------+
//| Check swing low position |
//+------------------------------------------------------------------+
bool IsSwingLow(int index, int left, int right)
{
double currentLow = Low[index];
for(int i = index - left; i < index; i++)
if(Low[i] <= currentLow)
return false;
for(int i = index + 1; i <= index + right; i++)
if(Low[i] < currentLow)
return false;
return true;
}
//+------------------------------------------------------------------+
//| Add new liquidity zone and draw horizontal ray |
//+------------------------------------------------------------------+
void AddLiquidityZone(datetime time, double price, int type)
{
if(zones_count >= MAX_ZONES)
{
Print("Max liquidity zones reached");
return;
}
string obj_name = "LiquidityRay_" + IntegerToString(time);
// Create horizontal ray extending to right
long obj_id = ObjectCreate(0,obj_name,OBJ_HLINE,0,0,price);
if(obj_id==0)
{
Print("Failed to create object: ",GetLastError());
return;
}
ObjectSetInteger(0,obj_name,OBJPROP_COLOR,LiquidityColor);
ObjectSetInteger(0,obj_name,OBJPROP_STYLE,STYLE_SOLID);
ObjectSetInteger(0,obj_name,OBJPROP_WIDTH,1);
ObjectSetInteger(0,obj_name,OBJPROP_RAY_RIGHT,true);
ObjectSetInteger(0,obj_name,OBJPROP_BACK,true);
zones[zones_count].time = time;
zones[zones_count].price = price;
zones[zones_count].type = type;
zones[zones_count].obj_id = obj_id;
zones[zones_count].active = true;
zones_count++;
}
//+------------------------------------------------------------------+
//| Delete liquidity zone (remove the object) |
//+------------------------------------------------------------------+
void DeleteLiquidityZone(int index)
{
if(index < 0 || index >= zones_count)
return;
string obj_name = ObjectName(0, index);
// Delete the object by name
ObjectDelete(0,ObjectName(0,zones[index].obj_id));
// Shift array elements left
for(int i=index; i<zones_count-1; i++)
zones[i] = zones[i+1];
zones_count--;
}
//+------------------------------------------------------------------+
//| Indicator iteration |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[])
{
if(rates_total < SwingLookback*2 + 10)
return 0;
// Inspect bars one time when new bar formed (prev_calculated < rates_total)
// We'll process bars only once to avoid drawing duplicate objects
static datetime last_time_bar = 0;
datetime cur_time = Time[rates_total-1];
if(cur_time == last_time_bar)
return prev_calculated; // no new bar formed
last_time_bar = cur_time;
int start_index = SwingLookback + 1;
int end_index = rates_total - SwingLookback - 2;
// Look for new swing highs/lows in last bars
// (can be optimized to check only recent bars)
for(int i = start_index; i < end_index; i++)
{
// Check for swing high
if(IsSwingHigh(i, SwingLookback, SwingLookback))
{
double level = High[i];
datetime t = Time[i];
// Check if zone already exists at this time - skip duplicates
bool exists = false;
for(int z=0; z<zones_count; z++)
{
if(zones[z].time == t && zones[z].price == level && zones[z].type == 1)
{
exists = true;
break;
}
}
if(!exists)
AddLiquidityZone(t, level, 1);
}
// Check for swing low
if(IsSwingLow(i, SwingLookback, SwingLookback))
{
double level = Low[i];
datetime t = Time[i];
bool exists = false;
for(int z=0; z<zones_count; z++)
{
if(zones[z].time == t && zones[z].price == level && zones[z].type == -1)
{
exists = true;
break;
}
}
if(!exists)
AddLiquidityZone(t, level, -1);
}
}
// Now check if price touched active zones, if yes, remove their rays
double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
for(int i=zones_count-1; i>=0; i--)
{
if(!zones[i].active)
continue;
if(zones[i].type == 1) // resistance zone
{
// If price touched or went above zone price, remove ray
if(Low[0] <= zones[i].price && High[0] >= zones[i].price)
{
string name = ObjectName(0, zones[i].obj_id);
ObjectDelete(0,name);
zones[i].active = false;
PrintFormat("Liquidity resistance zone at %.5f touched and deleted", zones[i].price);
}
}
else if(zones[i].type == -1) // support zone
{
if(Low[0] <= zones[i].price && High[0] >= zones[i].price)
{
string name = ObjectName(0, zones[i].obj_id);
ObjectDelete(0,name);
zones[i].active = false;
PrintFormat("Liquidity support zone at %.5f touched and deleted", zones[i].price);
}
}
}
return rates_total;
}
How to use:
Save the indicator code as LiquidityZones.mq5 in your Indicators folder.
Compile and attach it to any chart.
It will automatically detect swing highs/lows as liquidity zones.
Draw horizontal white rays at these zones extending to the right.
When the price (in any bar) touches or crosses that level, the corresponding ray disappears.
Notes & improvements:
In this demo, once a zone is touched, it deletes the ray. If you prefer to keep it and just stop extending the ray, you'd have to use a horizontal line (OBJ_HLINE) without ray right and manage its length by changing the endpoint — but it's a bit more complex.
You can also change ray colors or widths based on zone type.
This only scans once per new bar (when a new bar forms).
You can integrate the ray-drawing logic inside your EA if preferred— just be careful to separate object creation and deletion properly.
The zones array is limited to 50 zones here for simplicity.
If you want me to help you integrate this visualization logic directly inside your EA or with a modification, just ask!
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots 0
input int SwingLookback = 5; // Swing lookback bars
input color LiquidityColor = White;
struct LiquidityZone
{
datetime time; // Bar time where zone created (unique id)
double price; // Liquidity zone price
int type; // 1 = Swing High (resistance), -1 = Swing Low (support)
string ray_name; // Name of the horizontal ray object (extending right)
string line_name; // Name of horizontal line (fixed length after touched)
bool ray_active; // True if ray is drawn (before touched)
bool line_active; // True if fixed line is drawn (after touched)
};
#define MAX_ZONES 50
LiquidityZone zones[MAX_ZONES];
int zones_count = 0;
//+------------------------------------------------------------------+
//| Check swing high |
//+------------------------------------------------------------------+
bool IsSwingHigh(int index, int left, int right)
{
double currentHigh = High[index];
for(int i = index - left; i < index; i++)
if(High[i] >= currentHigh)
return false;
for(int i = index + 1; i <= index + right; i++)
if(High[i] > currentHigh)
return false;
return true;
}
//+------------------------------------------------------------------+
//| Check swing low |
//+------------------------------------------------------------------+
bool IsSwingLow(int index, int left, int right)
{
double currentLow = Low[index];
for(int i = index - left; i < index; i++)
if(Low[i] <= currentLow)
return false;
for(int i = index + 1; i <= index + right; i++)
if(Low[i] < currentLow)
return false;
return true;
}
//+------------------------------------------------------------------+
//| Create horizontal ray |
//+------------------------------------------------------------------+
bool CreateRay(string name, double price)
{
if(!ObjectCreate(0, name, OBJ_HLINE, 0, 0, price))
{
Print("Failed to create ray ", name, " Error: ", GetLastError());
return false;
}
ObjectSetInteger(0, name, OBJPROP_COLOR, LiquidityColor);
ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, true);
ObjectSetInteger(0, name, OBJPROP_BACK, true);
return true;
}
//+------------------------------------------------------------------+
//| Create horizontal line (fixed, no ray right) |
//+------------------------------------------------------------------+
bool CreateLine(string name, double price)
{
if(!ObjectCreate(0, name, OBJ_HLINE, 0, 0, price))
{
Print("Failed to create line ", name, " Error: ", GetLastError());
return false;
}
ObjectSetInteger(0, name, OBJPROP_COLOR, LiquidityColor);
ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT);
ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(0, name, OBJPROP_BACK, true);
return true;
}
//+------------------------------------------------------------------+
//| Add liquidity zone and draw initial ray |
//+------------------------------------------------------------------+
void AddLiquidityZone(datetime time, double price, int type)
{
if(zones_count >= MAX_ZONES)
{
Print("Max liquidity zones reached");
return;
}
string id_str = IntegerToString(time);
string rayName = "LiquidityRay_" + id_str;
string lineName = "LiquidityLine_" + id_str;
if(!CreateRay(rayName, price))
return;
zones[zones_count].time = time;
zones[zones_count].price = price;
zones[zones_count].type = type;
zones[zones_count].ray_name = rayName;
zones[zones_count].line_name = lineName;
zones[zones_count].ray_active = true;
zones[zones_count].line_active = false;
zones_count++;
}
//+------------------------------------------------------------------+
//| OnCalculate: main indicator loop |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double& price[])
{
if(rates_total < SwingLookback * 2 + 10)
return 0;
static datetime lastTime = 0;
datetime currTime = Time[rates_total - 1];
if(currTime == lastTime)
return prev_calculated; // no new bar
lastTime = currTime;
int start_index = SwingLookback + 1;
int end_index = rates_total - SwingLookback - 2;
// Find new swing highs / lows zones
for(int i = start_index; i < end_index; i++)
{
// Swing High
if(IsSwingHigh(i, SwingLookback, SwingLookback))
{
double level = High[i];
datetime t = Time[i];
bool exists = false;
for(int z = 0; z < zones_count; z++)
{
if(zones[z].time == t && zones[z].price == level && zones[z].type == 1)
{
exists = true;
break;
}
}
if(!exists)
AddLiquidityZone(t, level, 1);
}
// Swing Low
if(IsSwingLow(i, SwingLookback, SwingLookback))
{
double level = Low[i];
datetime t = Time[i];
bool exists = false;
for(int z = 0; z < zones_count; z++)
{
if(zones[z].time == t && zones[z].price == level && zones[z].type == -1)
{
exists = true;
break;
}
}
if(!exists)
AddLiquidityZone(t, level, -1);
}
}
// Update zones: check if price touched any active ray zones
double lastLow = Low[0];
double lastHigh = High[0];
for(int i = 0; i < zones_count; i++)
{
if(zones[i].ray_active)
{
// Check if current bar touches liquidity zone level
if(lastLow <= zones[i].price && lastHigh >= zones[i].price)
{
// Price touched zone => delete ray, draw fixed line instead
if(ObjectFind(0, zones[i].ray_name) >= 0)
ObjectDelete(0, zones[i].ray_name);
if(CreateLine(zones[i].line_name, zones[i].price))
{
zones[i].ray_active = false;
zones[i].line_active = true;
PrintFormat("Liquidity zone at %.5f touched: ray replaced by fixed line", zones[i].price);
}
}
}
}
return rates_total;
}
What changed?
Zones hold two names: for the ray and for the fixed line.
Initially, the liquidity zone is drawn as a ray extending infinitely right.
On bar updates, if price touches the zone price:
The ray object is deleted.
A horizontal line without ray_right is drawn at the same price.
The horizontal line remains there, showing the liquidity zone without extending further.
Usage:
Compile and attach this indicator to your chart.
You see white horizontal rays at liquidity zones.
When price touches a zone (based on bar low/high), the ray disappears and a dotted horizontal line stays, no longer extending.
Optional:
You can customize the color, line style, and width for rays and lines inside CreateRay and CreateLine functions.
If you want me to help integrate this into your EA with position management or anything else — just ask!
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots 0
input int SwingLookback = 5; // Swing lookback bars
input color LiquidityColor = White;
struct LiquidityZone
{
datetime time; // Bar time where zone created
double price; // Liquidity zone price
int type; // 1 = Swing High (resistance), -1 = Swing Low (support)
string ray_name; // Name of horizontal ray object
string line_name; // Name of horizontal line object
bool ray_active; // Whether the ray is currently active
bool line_active; // Whether fixed line is currently active
};
#define MAX_ZONES 50
LiquidityZone zones[MAX_ZONES];
int zones_count = 0;
// Check swing high at index
bool IsSwingHigh(int index, int left, int right)
{
double currentHigh = High[index];
for(int i = index - left; i < index; i++)
if(High[i] >= currentHigh)
return false;
for(int i = index + 1; i <= index + right; i++)
if(High[i] > currentHigh)
return false;
return true;
}
// Check swing low at index
bool IsSwingLow(int index, int left, int right)
{
double currentLow = Low[index];
for(int i = index - left; i < index; i++)
if(Low[i] <= currentLow)
return false;
for(int i = index + 1; i <= index + right; i++)
if(Low[i] < currentLow)
return false;
return true;
}
// Create horizontal ray
bool CreateRay(string name, double price)
{
if(!ObjectCreate(0, name, OBJ_HLINE, 0, 0, price))
{
Print("Failed to create ray ", name, " Error: ", GetLastError());
return false;
}
ObjectSetInteger(0, name, OBJPROP_COLOR, LiquidityColor);
ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, true);
ObjectSetInteger(0, name, OBJPROP_BACK, true);
return true;
}
// Create horizontal fixed line (no extending ray)
bool CreateLine(string name, double price)
{
if(!ObjectCreate(0, name, OBJ_HLINE, 0, 0, price))
{
Print("Failed to create line ", name, " Error: ", GetLastError());
return false;
}
ObjectSetInteger(0, name, OBJPROP_COLOR, LiquidityColor);
ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT);
ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(0, name, OBJPROP_BACK, true);
return true;
}
// Add liquidity zone and draw ray
void AddLiquidityZone(datetime time, double price, int type)
{
if(zones_count >= MAX_ZONES)
{
Print("Max liquidity zones reached");
return;
}
string id_str = IntegerToString(time);
string rayName = "LiquidityRay_" + id_str;
string lineName = "LiquidityLine_" + id_str;
if(!CreateRay(rayName, price))
return;
zones[zones_count].time = time;
zones[zones_count].price = price;
zones[zones_count].type = type;
zones[zones_count].ray_name = rayName;
zones[zones_count].line_name = lineName;
zones[zones_count].ray_active = true;
zones[zones_count].line_active = false;
zones_count++;
}
// Indicator main function
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[])
{
if(rates_total < SwingLookback * 2 + 10)
return 0;
static datetime lastTime = 0;
datetime currTime = Time[rates_total - 1];
if(currTime == lastTime)
return prev_calculated; // no new bar
lastTime = currTime;
int start_index = SwingLookback + 1;
int end_index = rates_total - SwingLookback - 2;
// Find new swing highs / lows zones
for(int i = start_index; i < end_index; i++)
{
// Swing High
if(IsSwingHigh(i, SwingLookback, SwingLookback))
{
double level = High[i];
datetime t = Time[i];
bool exists = false;
for(int z = 0; z < zones_count; z++)
{
if(zones[z].time == t && zones[z].price == level && zones[z].type == 1)
{
exists = true;
break;
}
}
if(!exists)
AddLiquidityZone(t, level, 1);
}
// Swing Low
if(IsSwingLow(i, SwingLookback, SwingLookback))
{
double level = Low[i];
datetime t = Time[i];
bool exists = false;
for(int z = 0; z < zones_count; z++)
{
if(zones[z].time == t && zones[z].price == level && zones[z].type == -1)
{
exists = true;
break;
}
}
if(!exists)
AddLiquidityZone(t, level, -1);
}
}
// Update zones: check if price touched any active ray zones
double lastLow = Low[0];
double lastHigh = High[0];
for(int i = 0; i < zones_count; i++)
{
if(zones[i].ray_active)
{
if(lastLow <= zones[i].price && lastHigh >= zones[i].price)
{
if(ObjectFind(0, zones[i].ray_name) >= 0)
ObjectDelete(0, zones[i].ray_name);
if(CreateLine(zones[i].line_name, zones[i].price))
{
zones[i].ray_active = false;
zones[i].line_active = true;
PrintFormat("Liquidity zone at %.5f touched: ray replaced by fixed line", zones[i].price);
}
}
}
}
return rates_total;
}
Key points:
The indicator uses predefined arrays: High[], Low[], Time[] which are globally available in indicator context.
Compile this as an Indicator (.mq5) — it will plot liquidity zones automatically.
Make sure you attach it to a chart with enough bars loaded.
Make sure not to put this code inside an EA .mq5 file or script, unless you modify it accordingly to fetch price data arrays differently.
If you want me to convert this logic for use in an EA or script where High[]/Low[] etc are not available implicitly, tell me and I will do that!
int OnInit()
{
return(INIT_SUCCEEDED);
}
void OnTick()
{
// Number of bars to query
int bars_needed = 100;
double highs[], lows[];
datetime times[];
// Copy High prices of last bars
if(CopyHigh(_Symbol, _Period, 0, bars_needed, highs) <= 0)
{
Print("Failed to copy highs");
return;
}
if(CopyLow(_Symbol, _Period, 0, bars_needed, lows) <= 0)
{
Print("Failed to copy lows");
return;
}
if(CopyTime(_Symbol, _Period, 0, bars_needed, times) <= 0)
{
Print("Failed to copy times");
return;
}
// Now highs[0] = latest bar high, highs[bars_needed-1] = oldest bar high
// To access High of bar with index i: highs[i], etc.
// Example: check if bar 10 is swing high:
int index = 10;
int left = 3, right = 3;
bool swingHigh = true;
double currentHigh = highs[index];
for(int i = index-left; i < index; i++)
{
if(i<0 || i>=bars_needed)
continue;
if(highs[i] >= currentHigh)
swingHigh = false;
}
for(int i = index+1; i <= index+right; i++)
{
if(i<0 || i>=bars_needed)
continue;
if(highs[i] > currentHigh)
swingHigh = false;
}
if(swingHigh)
{
PrintFormat("Bar %d is swing high at price %.5f", index, currentHigh);
}
}
Summary
Context
Arrays to use in your code
Notes
Indicator
Use High[], Low[], Time[] directly in OnCalculate
Saved in /Indicators/ folder
EA
Use CopyHigh(), CopyLow(), CopyTime() to load arrays
Saved in /Experts/ folder
Script
Same as EA
If you want, I can convert the entire liquidity zone indicator logic into an EA version that uses Copy...() functions and draws the objects dynamically on each tick or bar event.
Would you like me to do that?
//+------------------------------------------------------------------+
//| LiquidityEA.mq5|
//| Detects swing liquidity zones, draws rays & fixed lines |
//+------------------------------------------------------------------+
#property strict
input int SwingLookback = 5; // Bars left/right to confirm swing
input color LiquidityColor = White;
input int MaxZones = 50; // Max number of liquidity zones stored
// Structure to hold liquidity zone info
struct LiquidityZone
{
datetime time; // unique bar time identifier for the zone
double price;
int type; // 1 = swing high (resistance), -1 = swing low (support)
string ray_name; // Object name for ray
string line_name; // Object name for fixed line
bool ray_active; // True if ray is drawn (before touched)
bool line_active; // True if fixed line drawn (after touched)
};
LiquidityZone zones[];
int zones_count=0;
datetime lastBarTime=0;
//+------------------------------------------------------------------+
//| Check swing high in arrays |
//+------------------------------------------------------------------+
bool IsSwingHigh(const double &highs[], int index, int left, int right)
{
double currentHigh = highs[index];
for(int i = index - left; i < index; i++)
{
if(i < 0 || i >= ArraySize(highs))
continue;
if(highs[i] >= currentHigh)
return false;
}
for(int i = index + 1; i <= index + right; i++)
{
if(i < 0 || i >= ArraySize(highs))
continue;
if(highs[i] > currentHigh)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check swing low in arrays |
//+------------------------------------------------------------------+
bool IsSwingLow(const double &lows[], int index, int left, int right)
{
double currentLow = lows[index];
for(int i = index - left; i < index; i++)
{
if(i < 0 || i >= ArraySize(lows))
continue;
if(lows[i] <= currentLow)
return false;
}
for(int i = index + 1; i <= index + right; i++)
{
if(i < 0 || i >= ArraySize(lows))
continue;
if(lows[i] < currentLow)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Create horizontal ray object |
//+------------------------------------------------------------------+
bool CreateRay(string name, double price)
{
if(ObjectFind(0, name) >= 0) // Object exists, skip
return true;
bool created = ObjectCreate(0, name, OBJ_HLINE, 0, 0, price);
if(!created)
{
Print("Failed to create ray ", name, ". Error: ", GetLastError());
return false;
}
ObjectSetInteger(0, name, OBJPROP_COLOR, LiquidityColor);
ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, true);
ObjectSetInteger(0, name, OBJPROP_BACK, true);
return true;
}
//+------------------------------------------------------------------+
//| Create horizontal fixed line object |
//+------------------------------------------------------------------+
bool CreateLine(string name, double price)
{
if(ObjectFind(0, name) >= 0) // Object exists, skip
return true;
bool created = ObjectCreate(0, name, OBJ_HLINE, 0, 0, price);
if(!created)
{
Print("Failed to create line ", name, ". Error: ", GetLastError());
return false;
}
ObjectSetInteger(0, name, OBJPROP_COLOR, LiquidityColor);
ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT);
ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(0, name, OBJPROP_BACK, true);
return true;
}
//+------------------------------------------------------------------+
//| Add liquidity zone and draw ray |
//+------------------------------------------------------------------+
void AddLiquidityZone(datetime time, double price, int type)
{
if(zones_count >= MaxZones)
{
Print("Max zones limit reached. Cannot add more zones.");
return;
}
string id_str = IntegerToString(time);
string rayName = "LiquidityRay_" + id_str;
string lineName = "LiquidityLine_" + id_str;
if(!CreateRay(rayName, price))
return;
LiquidityZone zone;
zone.time = time;
zone.price = price;
zone.type = type;
zone.ray_name = rayName;
zone.line_name = lineName;
zone.ray_active = true;
zone.line_active = false;
ArrayResize(zones, zones_count + 1);
zones[zones_count] = zone;
zones_count++;
}
//+------------------------------------------------------------------+
//| Check if price touched liquidity zones & update drawings |
//+------------------------------------------------------------------+
void UpdateZones(double lastLow, double lastHigh)
{
for(int i = 0; i < zones_count; i++)
{
if(zones[i].ray_active)
{
if(lastLow <= zones[i].price && lastHigh >= zones[i].price)
{
// Price touched zone -> switch from ray to fixed line
if(ObjectFind(0, zones[i].ray_name) >= 0)
ObjectDelete(0, zones[i].ray_name);
if(CreateLine(zones[i].line_name, zones[i].price))
{
zones[i].ray_active = false;
zones[i].line_active = true;
PrintFormat("Liquidity zone at %.5f touched: ray replaced by fixed line", zones[i].price);
}
}
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// We'll run liquidity zone detection once per new bar
MqlRates rates[];
int copied = CopyRates(_Symbol, _Period, 0, 200, rates);
if(copied <= 0)
{
Print("Failed to get bars");
return;
}
datetime currentBarTime = rates[0].time;
if(currentBarTime == lastBarTime)
return; // No new bar
lastBarTime = currentBarTime;
// Prepare separate arrays for highs/lows/time to make swing detection easier
double highs[], lows[];
ArrayResize(highs, copied);
ArrayResize(lows, copied);
for(int i=0; i<copied; i++)
{
highs[i] = rates[i].high;
lows[i] = rates[i].low;
}
// Search for new swing zones in the last bars (avoid very recent for less false signals)
int start_index = SwingLookback + 1;
int end_index = copied - SwingLookback - 1;
for(int i = start_index; i < end_index; i++)
{
// Swing High
if(IsSwingHigh(highs, i, SwingLookback, SwingLookback))
{
double level = highs[i];
datetime t = rates[i].time;
// Prevent duplicates
bool exists = false;
for(int z=0; z<zones_count; z++)
{
if(zones[z].time == t && zones[z].price == level && zones[z].type == 1)
{
exists = true;
break;
}
}
if(!exists)
AddLiquidityZone(t, level, 1); // resistance zone
}
// Swing Low
if(IsSwingLow(lows, i, SwingLookback, SwingLookback))
{
double level = lows[i];
datetime t = rates[i].time;
bool exists = false;
for(int z=0; z<zones_count; z++)
{
if(zones[z].time == t && zones[z].price == level && zones[z].type == -1)
{
exists = true;
break;
}
}
if(!exists)
AddLiquidityZone(t, level, -1); // support zone
}
}
// Update and change rays to lines if price touched zones
UpdateZones(rates[0].low, rates[0].high);
}
//+------------------------------------------------------------------+
How full example works:
On every tick, we copy 200 bars with CopyRates().
Detect swing highs and lows according to your lookback using the copied data.
If a new swing high/low (liquidity zone) is found and not already recorded, add it, and draw a white horizontal ray extending to the right.
When price touches the zone (current bar low <= zone price <= high), replace the ray with a fixed dotted horizontal line that no longer extends.
All liquidity zones are stored in memory in an array.
The maximum number of zones is limited by MaxZones (default 50).
To use:
Copy-paste this code into a new .mq5 Expert Advisor in MetaEditor (e.g., LiquidityZone_EA.mq5).
Compile and attach to your desired chart.
You should see white horizontal rays drawn at swing highs/lows.
When price touches them, each ray replaced by a fixed dotted line.
Next steps:
You can integrate your trading logic with these zones inside OnTick() or OnTimer().
Manage orders with appropriate conditions.
Add options for deleting old zones or adjusting visual styles.
If you want, I can help you extend this EA to trade reversals, liquidity swap entries, or other conditions you need in your first message.
Let me know if you want me to add that or any other feature!