create a mql4 indicator that will accurately draw supply and demand zones based on price…
- User
create a mql4 indicator that will accurately draw supply and demand zones based on price action and volume
Assistant
//+------------------------------------------------------------------+ //| Supply_Demand_Zones.mq4 | //| | //+------------------------------------------------------------------+ #property copyright "Copyright 2025" #property version "1.00" #property strict #property indicator_chart_window // Input parameters input int LookBack = 100; // Number of bars to analyze input int ZoneStrength = 3; // Minimum strength for a valid zone (1-10) input double VolumeFactor = 1.5; // Volume must be this times the average input int MaxZones = 10; // Maximum number of zones to display input color SupplyColor = clrRed; // Color for supply zones input color DemandColor = clrGreen; // Color for demand zones input int ZoneTransparency = 30; // Transparency level for zones (0-255) input bool DeleteOldZones = true; // Delete zones that price has broken through // Global variables struct Zone { datetime time; // Time of zone creation double high; // Upper price of zone double low; // Lower price of zone bool isSupply; // True for supply, false for demand double strength; // Zone strength (1-10) string objName; // Object name for the zone on chart }; Zone g_Zones[]; // Array to store identified zones //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { // Initialize indicator buffers // Delete all previous zone objects if requested if(DeleteOldZones) DeleteAllZones(); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Custom indicator deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Clean up by removing all zone objects DeleteAllZones(); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { // Don't recalculate if not enough bars if(rates_total < LookBack + 10) return(0); // Only calculate if this is a new bar or first calculation if(prev_calculated > 0 && rates_total == prev_calculated) return(rates_total); // Calculate average volume double avgVolume = 0; for(int i = 0; i < LookBack; i++) { avgVolume += volume[i]; } avgVolume /= LookBack; // Find and analyze potential zones IdentifyZones(time, open, high, low, close, volume, avgVolume); // Draw the zones on the chart DrawZones(); return(rates_total); } //+------------------------------------------------------------------+ //| Identify potential supply and demand zones | //+------------------------------------------------------------------+ void IdentifyZones(const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { // Clear previous zones ArrayResize(g_Zones, 0); // Temporary array for potential zones Zone tempZones[]; int zoneCount = 0; // Loop through bars to find potential zones for(int i = 5; i < LookBack; i++) { // Check for potential supply zone (price moves up then sharply down) if(IsSupplyZone(i, open, high, low, close, volume, avgVolume)) { // Create a new zone ArrayResize(tempZones, zoneCount + 1); tempZones[zoneCount].time = time[i]; tempZones[zoneCount].high = high[i]; tempZones[zoneCount].low = MathMin(open[i], close[i]); tempZones[zoneCount].isSupply = true; tempZones[zoneCount].strength = CalculateZoneStrength(i, true, open, high, low, close, volume, avgVolume); tempZones[zoneCount].objName = "SupplyZone_" + TimeToString(time[i]); zoneCount++; } // Check for potential demand zone (price moves down then sharply up) if(IsDemandZone(i, open, high, low, close, volume, avgVolume)) { // Create a new zone ArrayResize(tempZones, zoneCount + 1); tempZones[zoneCount].time = time[i]; tempZones[zoneCount].high = MathMax(open[i], close[i]); tempZones[zoneCount].low = low[i]; tempZones[zoneCount].isSupply = false; tempZones[zoneCount].strength = CalculateZoneStrength(i, false, open, high, low, close, volume, avgVolume); tempZones[zoneCount].objName = "DemandZone_" + TimeToString(time[i]); zoneCount++; } } // Sort zones by strength SortZonesByStrength(tempZones); // Select top zones based on MaxZones parameter int numZones = MathMin(zoneCount, MaxZones); ArrayResize(g_Zones, numZones); for(int i = 0; i < numZones; i++) { g_Zones[i] = tempZones[i]; } } //+------------------------------------------------------------------+ //| Check if bar forms a supply zone | //+------------------------------------------------------------------+ bool IsSupplyZone(int bar, const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { // Check if we have a bearish reversal bar with higher volume bool isBearish = close[bar] < open[bar]; bool highVolume = volume[bar] > avgVolume * VolumeFactor; // Check if price moved up before reversing down bool priorUpMove = false; // Check the previous 3 bars for upward movement double priorHighest = high[bar+1]; double priorLowest = low[bar+1]; for(int i = bar+1; i <= bar+3; i++) { if(high[i] > priorHighest) priorHighest = high[i]; if(low[i] < priorLowest) priorLowest = low[i]; } priorUpMove = (priorHighest - priorLowest) / priorLowest > 0.001; // 0.1% minimum move // We have a supply zone if: // 1. Current bar is bearish // 2. Higher than normal volume // 3. Price moved up before reversing // 4. Current bar has a notable body (not a doji) return isBearish && highVolume && priorUpMove && (MathAbs(close[bar] - open[bar]) > (high[bar] - low[bar]) * 0.3); } //+------------------------------------------------------------------+ //| Check if bar forms a demand zone | //+------------------------------------------------------------------+ bool IsDemandZone(int bar, const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { // Check if we have a bullish reversal bar with higher volume bool isBullish = close[bar] > open[bar]; bool highVolume = volume[bar] > avgVolume * VolumeFactor; // Check if price moved down before reversing up bool priorDownMove = false; // Check the previous 3 bars for downward movement double priorHighest = high[bar+1]; double priorLowest = low[bar+1]; for(int i = bar+1; i <= bar+3; i++) { if(high[i] > priorHighest) priorHighest = high[i]; if(low[i] < priorLowest) priorLowest = low[i]; } priorDownMove = (priorHighest - priorLowest) / priorLowest > 0.001; // 0.1% minimum move // We have a demand zone if: // 1. Current bar is bullish // 2. Higher than normal volume // 3. Price moved down before reversing // 4. Current bar has a notable body (not a doji) return isBullish && highVolume && priorDownMove && (MathAbs(close[bar] - open[bar]) > (high[bar] - low[bar]) * 0.3); } //+------------------------------------------------------------------+ //| Calculate the strength of a zone (1-10) | //+------------------------------------------------------------------+ double CalculateZoneStrength(int bar, bool isSupply, const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { double strength = 0; // Factor 1: Volume strength (0-3 points) double volRatio = volume[bar] / avgVolume; if(volRatio > 3.0) strength += 3.0; else if(volRatio > 2.0) strength += 2.0; else if(volRatio > VolumeFactor) strength += 1.0; // Factor 2: Candle body size (0-2 points) double bodyRatio = MathAbs(close[bar] - open[bar]) / (high[bar] - low[bar]); if(bodyRatio > 0.7) strength += 2.0; else if(bodyRatio > 0.5) strength += 1.0; // Factor 3: Reversal strength (0-3 points) if(isSupply) { // For supply: how strong was the drop after the high? double dropPercent = 0; for(int i = bar-1; i >= MathMax(0, bar-3); i--) { dropPercent = MathMax(dropPercent, (high[bar] - low[i]) / high[bar]); } if(dropPercent > 0.02) strength += 3.0; // 2% or more else if(dropPercent > 0.01) strength += 2.0; // 1% or more else if(dropPercent > 0.005) strength += 1.0; // 0.5% or more } else { // For demand: how strong was the rise after the low? double risePercent = 0; for(int i = bar-1; i >= MathMax(0, bar-3); i--) { risePercent = MathMax(risePercent, (high[i] - low[bar]) / low[bar]); } if(risePercent > 0.02) strength += 3.0; // 2% or more else if(risePercent > 0.01) strength += 2.0; // 1% or more else if(risePercent > 0.005) strength += 1.0; // 0.5% or more } // Factor 4: Untested zone (0-2 points) // Check if the zone has been tested/touched since its formation bool untested = true; for(int i = bar-1; i >= 0; i--) { if(isSupply) { if(high[i] > low[bar]) { untested = false; break; } } else { if(low[i] < high[bar]) { untested = false; break; } } } if(untested) strength += 2.0; // Ensure strength is at least 1 and at most 10 return MathMax(1, MathMin(10, strength)); } //+------------------------------------------------------------------+ //| Sort zones by strength (highest first) | //+------------------------------------------------------------------+ void SortZonesByStrength(Zone &zones[]) { int size = ArraySize(zones); if(size <= 1) return; // Simple bubble sort for(int i = 0; i < size-1; i++) { for(int j = 0; j < size-i-1; j++) { if(zones[j].strength < zones[j+1].strength) { Zone temp = zones[j]; zones[j] = zones[j+1]; zones[j+1] = temp; } } } } //+------------------------------------------------------------------+ //| Draw zones on the chart | //+------------------------------------------------------------------+ void DrawZones() { // First clear old zones DeleteAllZones(); // Draw each zone for(int i = 0; i < ArraySize(g_Zones); i++) { // Skip zones with strength less than ZoneStrength parameter if(g_Zones[i].strength < ZoneStrength) continue; // Determine zone color based on type color zoneColor = g_Zones[i].isSupply ? SupplyColor : DemandColor; // Create rectangle object string objName = g_Zones[i].objName; // Calculate rectangle coordinates datetime time1 = g_Zones[i].time; datetime time2 = Time[0] + (Time[0] - Time[1]) * 20; // Extend to the right double price1 = g_Zones[i].high; double price2 = g_Zones[i].low; // Draw the rectangle ObjectCreate(0, objName, OBJ_RECTANGLE, 0, time1, price1, time2, price2); ObjectSetInteger(0, objName, OBJPROP_COLOR, zoneColor); ObjectSetInteger(0, objName, OBJPROP_FILL, true); ObjectSetInteger(0, objName, OBJPROP_BACK, true); ObjectSetInteger(0, objName, OBJPROP_SELECTABLE, false); ObjectSetInteger(0, objName, OBJPROP_SELECTED, false); ObjectSetInteger(0, objName, OBJPROP_HIDDEN, true); ObjectSetInteger(0, objName, OBJPROP_ZORDER, 0); // Set transparency ObjectSetInteger(0, objName, OBJPROP_TRANSPARENCY, ZoneTransparency); // Add label with strength string labelName = "Label_" + objName; string labelText = g_Zones[i].isSupply ? "Supply" : "Demand"; labelText += " (" + DoubleToString(g_Zones[i].strength, 1) + ")"; ObjectCreate(0, labelName, OBJ_TEXT, 0, time1, g_Zones[i].isSupply ? price1 : price2); ObjectSetString(0, labelName, OBJPROP_TEXT, labelText); ObjectSetInteger(0, labelName, OBJPROP_COLOR, zoneColor); ObjectSetInteger(0, labelName, OBJPROP_FONTSIZE, 8); ObjectSetInteger(0, labelName, OBJPROP_SELECTABLE, false); } } //+------------------------------------------------------------------+ //| Delete all zone objects | //+------------------------------------------------------------------+ void DeleteAllZones() { for(int i = ObjectsTotal() - 1; i >= 0; i--) { string objName = ObjectName(i); if(StringFind(objName, "SupplyZone_") >= 0 || StringFind(objName, "DemandZone_") >= 0 || StringFind(objName, "Label_") >= 0) { ObjectDelete(objName); } } } //+------------------------------------------------------------------+Would you like me to explain how this code works or break down any specific parts of it?
- User
possible loss of data due to type conversion Super zone.mq4 79 17 'OBJPROP_TRANSPARENCY' - undeclared identifier Super zone.mq4 373 36 1 errors, 1 warnings 2 2
Assistant
Let me fix those issues:
//+------------------------------------------------------------------+ //| Supply_Demand_Zones.mq4 | //| | //+------------------------------------------------------------------+ #property copyright "Copyright 2025" #property version "1.00" #property strict #property indicator_chart_window // Input parameters input int LookBack = 100; // Number of bars to analyze input int ZoneStrength = 3; // Minimum strength for a valid zone (1-10) input double VolumeFactor = 1.5; // Volume must be this times the average input int MaxZones = 10; // Maximum number of zones to display input color SupplyColor = clrRed; // Color for supply zones input color DemandColor = clrGreen; // Color for demand zones input int ZoneTransparency = 30; // Transparency level for zones (0-255) input bool DeleteOldZones = true; // Delete zones that price has broken through // Global variables struct Zone { datetime time; // Time of zone creation double high; // Upper price of zone double low; // Lower price of zone bool isSupply; // True for supply, false for demand double strength; // Zone strength (1-10) string objName; // Object name for the zone on chart }; Zone g_Zones[]; // Array to store identified zones //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { // Initialize indicator buffers // Delete all previous zone objects if requested if(DeleteOldZones) DeleteAllZones(); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Custom indicator deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Clean up by removing all zone objects DeleteAllZones(); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { // Don't recalculate if not enough bars if(rates_total < LookBack + 10) return(0); // Only calculate if this is a new bar or first calculation if(prev_calculated > 0 && rates_total == prev_calculated) return(rates_total); // Calculate average volume double avgVolume = 0; for(int i = 0; i < LookBack; i++) { avgVolume += (double)volume[i]; // Fixed: Explicit casting to avoid data loss warning } avgVolume /= LookBack; // Find and analyze potential zones IdentifyZones(time, open, high, low, close, volume, avgVolume); // Draw the zones on the chart DrawZones(); return(rates_total); } //+------------------------------------------------------------------+ //| Identify potential supply and demand zones | //+------------------------------------------------------------------+ void IdentifyZones(const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { // Clear previous zones ArrayResize(g_Zones, 0); // Temporary array for potential zones Zone tempZones[]; int zoneCount = 0; // Loop through bars to find potential zones for(int i = 5; i < LookBack; i++) { // Check for potential supply zone (price moves up then sharply down) if(IsSupplyZone(i, open, high, low, close, volume, avgVolume)) { // Create a new zone ArrayResize(tempZones, zoneCount + 1); tempZones[zoneCount].time = time[i]; tempZones[zoneCount].high = high[i]; tempZones[zoneCount].low = MathMin(open[i], close[i]); tempZones[zoneCount].isSupply = true; tempZones[zoneCount].strength = CalculateZoneStrength(i, true, open, high, low, close, volume, avgVolume); tempZones[zoneCount].objName = "SupplyZone_" + TimeToString(time[i]); zoneCount++; } // Check for potential demand zone (price moves down then sharply up) if(IsDemandZone(i, open, high, low, close, volume, avgVolume)) { // Create a new zone ArrayResize(tempZones, zoneCount + 1); tempZones[zoneCount].time = time[i]; tempZones[zoneCount].high = MathMax(open[i], close[i]); tempZones[zoneCount].low = low[i]; tempZones[zoneCount].isSupply = false; tempZones[zoneCount].strength = CalculateZoneStrength(i, false, open, high, low, close, volume, avgVolume); tempZones[zoneCount].objName = "DemandZone_" + TimeToString(time[i]); zoneCount++; } } // Sort zones by strength SortZonesByStrength(tempZones); // Select top zones based on MaxZones parameter int numZones = MathMin(zoneCount, MaxZones); ArrayResize(g_Zones, numZones); for(int i = 0; i < numZones; i++) { g_Zones[i] = tempZones[i]; } } //+------------------------------------------------------------------+ //| Check if bar forms a supply zone | //+------------------------------------------------------------------+ bool IsSupplyZone(int bar, const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { // Check if we have a bearish reversal bar with higher volume bool isBearish = close[bar] < open[bar]; bool highVolume = (double)volume[bar] > avgVolume * VolumeFactor; // Check if price moved up before reversing down bool priorUpMove = false; // Check the previous 3 bars for upward movement double priorHighest = high[bar+1]; double priorLowest = low[bar+1]; for(int i = bar+1; i <= bar+3; i++) { if(high[i] > priorHighest) priorHighest = high[i]; if(low[i] < priorLowest) priorLowest = low[i]; } priorUpMove = (priorHighest - priorLowest) / priorLowest > 0.001; // 0.1% minimum move // We have a supply zone if: // 1. Current bar is bearish // 2. Higher than normal volume // 3. Price moved up before reversing // 4. Current bar has a notable body (not a doji) return isBearish && highVolume && priorUpMove && (MathAbs(close[bar] - open[bar]) > (high[bar] - low[bar]) * 0.3); } //+------------------------------------------------------------------+ //| Check if bar forms a demand zone | //+------------------------------------------------------------------+ bool IsDemandZone(int bar, const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { // Check if we have a bullish reversal bar with higher volume bool isBullish = close[bar] > open[bar]; bool highVolume = (double)volume[bar] > avgVolume * VolumeFactor; // Check if price moved down before reversing up bool priorDownMove = false; // Check the previous 3 bars for downward movement double priorHighest = high[bar+1]; double priorLowest = low[bar+1]; for(int i = bar+1; i <= bar+3; i++) { if(high[i] > priorHighest) priorHighest = high[i]; if(low[i] < priorLowest) priorLowest = low[i]; } priorDownMove = (priorHighest - priorLowest) / priorLowest > 0.001; // 0.1% minimum move // We have a demand zone if: // 1. Current bar is bullish // 2. Higher than normal volume // 3. Price moved down before reversing // 4. Current bar has a notable body (not a doji) return isBullish && highVolume && priorDownMove && (MathAbs(close[bar] - open[bar]) > (high[bar] - low[bar]) * 0.3); } //+------------------------------------------------------------------+ //| Calculate the strength of a zone (1-10) | //+------------------------------------------------------------------+ double CalculateZoneStrength(int bar, bool isSupply, const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { double strength = 0; // Factor 1: Volume strength (0-3 points) double volRatio = (double)volume[bar] / avgVolume; if(volRatio > 3.0) strength += 3.0; else if(volRatio > 2.0) strength += 2.0; else if(volRatio > VolumeFactor) strength += 1.0; // Factor 2: Candle body size (0-2 points) double bodyRatio = MathAbs(close[bar] - open[bar]) / (high[bar] - low[bar]); if(bodyRatio > 0.7) strength += 2.0; else if(bodyRatio > 0.5) strength += 1.0; // Factor 3: Reversal strength (0-3 points) if(isSupply) { // For supply: how strong was the drop after the high? double dropPercent = 0; for(int i = bar-1; i >= MathMax(0, bar-3); i--) { dropPercent = MathMax(dropPercent, (high[bar] - low[i]) / high[bar]); } if(dropPercent > 0.02) strength += 3.0; // 2% or more else if(dropPercent > 0.01) strength += 2.0; // 1% or more else if(dropPercent > 0.005) strength += 1.0; // 0.5% or more } else { // For demand: how strong was the rise after the low? double risePercent = 0; for(int i = bar-1; i >= MathMax(0, bar-3); i--) { risePercent = MathMax(risePercent, (high[i] - low[bar]) / low[bar]); } if(risePercent > 0.02) strength += 3.0; // 2% or more else if(risePercent > 0.01) strength += 2.0; // 1% or more else if(risePercent > 0.005) strength += 1.0; // 0.5% or more } // Factor 4: Untested zone (0-2 points) // Check if the zone has been tested/touched since its formation bool untested = true; for(int i = bar-1; i >= 0; i--) { if(isSupply) { if(high[i] > low[bar]) { untested = false; break; } } else { if(low[i] < high[bar]) { untested = false; break; } } } if(untested) strength += 2.0; // Ensure strength is at least 1 and at most 10 return MathMax(1, MathMin(10, strength)); } //+------------------------------------------------------------------+ //| Sort zones by strength (highest first) | //+------------------------------------------------------------------+ void SortZonesByStrength(Zone &zones[]) { int size = ArraySize(zones); if(size <= 1) return; // Simple bubble sort for(int i = 0; i < size-1; i++) { for(int j = 0; j < size-i-1; j++) { if(zones[j].strength < zones[j+1].strength) { Zone temp = zones[j]; zones[j] = zones[j+1]; zones[j+1] = temp; } } } } //+------------------------------------------------------------------+ //| Draw zones on the chart | //+------------------------------------------------------------------+ void DrawZones() { // First clear old zones DeleteAllZones(); // Draw each zone for(int i = 0; i < ArraySize(g_Zones); i++) { // Skip zones with strength less than ZoneStrength parameter if(g_Zones[i].strength < ZoneStrength) continue; // Determine zone color based on type color zoneColor = g_Zones[i].isSupply ? SupplyColor : DemandColor; // Create rectangle object string objName = g_Zones[i].objName; // Calculate rectangle coordinates datetime time1 = g_Zones[i].time; datetime time2 = Time[0] + (Time[0] - Time[1]) * 20; // Extend to the right double price1 = g_Zones[i].high; double price2 = g_Zones[i].low; // Create a color with transparency (using RGB with alpha) // Convert transparency from 0-255 to 0-100% int alpha = 255 - ZoneTransparency; // Make sure alpha is within bounds if(alpha < 0) alpha = 0; if(alpha > 255) alpha = 255; // Draw the rectangle ObjectCreate(0, objName, OBJ_RECTANGLE, 0, time1, price1, time2, price2); ObjectSetInteger(0, objName, OBJPROP_COLOR, zoneColor); ObjectSetInteger(0, objName, OBJPROP_FILL, true); ObjectSetInteger(0, objName, OBJPROP_BACK, true); ObjectSetInteger(0, objName, OBJPROP_SELECTABLE, false); ObjectSetInteger(0, objName, OBJPROP_SELECTED, false); ObjectSetInteger(0, objName, OBJPROP_HIDDEN, true); ObjectSetInteger(0, objName, OBJPROP_ZORDER, 0); // For MQL4, transparency is handled by setting the object's background ObjectSetInteger(0, objName, OBJPROP_BGCOLOR, zoneColor); // Add label with strength string labelName = "Label_" + objName; string labelText = g_Zones[i].isSupply ? "Supply" : "Demand"; labelText += " (" + DoubleToString(g_Zones[i].strength, 1) + ")"; ObjectCreate(0, labelName, OBJ_TEXT, 0, time1, g_Zones[i].isSupply ? price1 : price2); ObjectSetString(0, labelName, OBJPROP_TEXT, labelText); ObjectSetInteger(0, labelName, OBJPROP_COLOR, zoneColor); ObjectSetInteger(0, labelName, OBJPROP_FONTSIZE, 8); ObjectSetInteger(0, labelName, OBJPROP_SELECTABLE, false); } } //+------------------------------------------------------------------+ //| Delete all zone objects | //+------------------------------------------------------------------+ void DeleteAllZones() { for(int i = ObjectsTotal() - 1; i >= 0; i--) { string objName = ObjectName(i); if(StringFind(objName, "SupplyZone_") >= 0 || StringFind(objName, "DemandZone_") >= 0 || StringFind(objName, "Label_") >= 0) { ObjectDelete(objName); } } } //+------------------------------------------------------------------+I fixed the two issues:
-
Added explicit type casting from long to double for volume data to avoid the "possible loss of data due to type conversion" warning.
-
Removed OBJPROP_TRANSPARENCY (which isn't available in MQL4) and instead used OBJPROP_BGCOLOR to set the background color. In MQL4, transparency is typically handled through colors rather than as a separate property.
These changes should resolve the errors and warnings you encountered.
-
- User
there is no zones displaying
Assistant
Let's fix the issue with zones not displaying. There are several possible issues that could be causing this problem. I'll modify the code to address the most likely causes:
//+------------------------------------------------------------------+ //| Supply_Demand_Zones.mq4 | //| | //+------------------------------------------------------------------+ #property copyright "Copyright 2025" #property version "1.00" #property strict #property indicator_chart_window // Input parameters input int LookBack = 100; // Number of bars to analyze input int ZoneStrength = 1; // Minimum strength for a valid zone (1-10) input double VolumeFactor = 1.2; // Volume must be this times the average input int MaxZones = 10; // Maximum number of zones to display input color SupplyColor = clrCrimson; // Color for supply zones input color DemandColor = clrForestGreen; // Color for demand zones input int ZoneOpacity = 70; // Opacity level for zones (0-100) input bool DeleteOldZones = true; // Delete zones that price has broken through input bool ExtendZones = true; // Extend zones to the right of the chart // Global variables struct Zone { datetime time; // Time of zone creation double high; // Upper price of zone double low; // Lower price of zone bool isSupply; // True for supply, false for demand double strength; // Zone strength (1-10) string objName; // Object name for the zone on chart }; Zone g_Zones[]; // Array to store identified zones //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { // Delete all previous zone objects if requested if(DeleteOldZones) DeleteAllZones(); // Set buffer styles IndicatorShortName("Supply and Demand Zones"); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Custom indicator deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Clean up by removing all zone objects DeleteAllZones(); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { // Don't recalculate if not enough bars if(rates_total < LookBack + 10) return(rates_total); // Calculate average volume double avgVolume = 0; for(int i = 0; i < LookBack; i++) { avgVolume += (double)tick_volume[i]; // Using tick volume which is always available } avgVolume /= LookBack; // Find and analyze potential zones IdentifyZones(time, open, high, low, close, tick_volume, avgVolume); // Draw the zones on the chart DrawZones(); return(rates_total); } //+------------------------------------------------------------------+ //| Identify potential supply and demand zones | //+------------------------------------------------------------------+ void IdentifyZones(const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { // Clear previous zones ArrayResize(g_Zones, 0); // Temporary array for potential zones Zone tempZones[]; int zoneCount = 0; // Loop through bars to find potential zones for(int i = 5; i < LookBack && i < Bars; i++) { // Check for potential supply zone if(close[i] < open[i] && // Bearish candle (double)volume[i] > avgVolume * VolumeFactor && // Higher volume high[i] > high[i+1] && // Higher high close[i] < open[i+1]) // Strong reversal { // Create a new zone ArrayResize(tempZones, zoneCount + 1); tempZones[zoneCount].time = time[i]; tempZones[zoneCount].high = high[i]; tempZones[zoneCount].low = MathMin(open[i], close[i]); tempZones[zoneCount].isSupply = true; tempZones[zoneCount].strength = CalculateZoneStrength(i, true, open, high, low, close, volume, avgVolume); tempZones[zoneCount].objName = "SupplyZone_" + IntegerToString(i); zoneCount++; } // Check for potential demand zone if(close[i] > open[i] && // Bullish candle (double)volume[i] > avgVolume * VolumeFactor && // Higher volume low[i] < low[i+1] && // Lower low close[i] > open[i+1]) // Strong reversal { // Create a new zone ArrayResize(tempZones, zoneCount + 1); tempZones[zoneCount].time = time[i]; tempZones[zoneCount].high = MathMax(open[i], close[i]); tempZones[zoneCount].low = low[i]; tempZones[zoneCount].isSupply = false; tempZones[zoneCount].strength = CalculateZoneStrength(i, false, open, high, low, close, volume, avgVolume); tempZones[zoneCount].objName = "DemandZone_" + IntegerToString(i); zoneCount++; } } // Sort zones by strength SortZonesByStrength(tempZones); // Select top zones based on MaxZones parameter int numZones = MathMin(zoneCount, MaxZones); ArrayResize(g_Zones, numZones); for(int i = 0; i < numZones; i++) { g_Zones[i] = tempZones[i]; } // Debug message if(numZones > 0) Print("Found ", numZones, " zones"); else Print("No zones found. Try adjusting parameters."); } //+------------------------------------------------------------------+ //| Calculate the strength of a zone (1-10) | //+------------------------------------------------------------------+ double CalculateZoneStrength(int bar, bool isSupply, const double &open[], const double &high[], const double &low[], const double &close[], const long &volume[], double avgVolume) { double strength = 1.0; // Base strength // Factor 1: Volume strength (0-3 points) double volRatio = (double)volume[bar] / avgVolume; if(volRatio > 3.0) strength += 3.0; else if(volRatio > 2.0) strength += 2.0; else if(volRatio > VolumeFactor) strength += 1.0; // Factor 2: Candle body size (0-2 points) double bodyRatio = MathAbs(close[bar] - open[bar]) / (high[bar] - low[bar]); if(bodyRatio > 0.7) strength += 2.0; else if(bodyRatio > 0.5) strength += 1.0; // Factor 3: Reversal strength (0-3 points) double moveStrength = 0; if(isSupply) { // For supply: how strong was the previous up move? double upMove = (high[bar] - low[bar+3]) / low[bar+3] * 100; // Percentage move if(upMove > 1.0) moveStrength += 1.0; if(upMove > 2.0) moveStrength += 1.0; if(upMove > 3.0) moveStrength += 1.0; } else { // For demand: how strong was the previous down move? double downMove = (high[bar+3] - low[bar]) / low[bar] * 100; // Percentage move if(downMove > 1.0) moveStrength += 1.0; if(downMove > 2.0) moveStrength += 1.0; if(downMove > 3.0) moveStrength += 1.0; } strength += moveStrength; // Factor 4: Recent test (0-2 points) bool recentlyTested = false; for(int i = bar-1; i >= MathMax(0, bar-20); i--) { if(isSupply) { if(high[i] > tempZones[zoneCount].low && high[i] < tempZones[zoneCount].high) { recentlyTested = true; break; } } else { if(low[i] < tempZones[zoneCount].high && low[i] > tempZones[zoneCount].low) { recentlyTested = true; break; } } } if(!recentlyTested) strength += 2.0; // Ensure strength is at least 1 and at most 10 return MathMax(1, MathMin(10, strength)); } //+------------------------------------------------------------------+ //| Sort zones by strength (highest first) | //+------------------------------------------------------------------+ void SortZonesByStrength(Zone &zones[]) { int size = ArraySize(zones); if(size <= 1) return; // Simple bubble sort for(int i = 0; i < size-1; i++) { for(int j = 0; j < size-i-1; j++) { if(zones[j].strength < zones[j+1].strength) { Zone temp = zones[j]; zones[j] = zones[j+1]; zones[j+1] = temp; } } } } //+------------------------------------------------------------------+ //| Draw zones on the chart | //+------------------------------------------------------------------+ void DrawZones() { // First clear old zones DeleteAllZones(); int count = ArraySize(g_Zones); if(count == 0) return; // No zones to draw // Draw each zone for(int i = 0; i < count; i++) { // Skip zones with strength less than ZoneStrength parameter if(g_Zones[i].strength < ZoneStrength) continue; // Determine zone color based on type color zoneColor = g_Zones[i].isSupply ? SupplyColor : DemandColor; // Create rectangle object string objName = g_Zones[i].objName; // Calculate rectangle coordinates datetime time1 = g_Zones[i].time; datetime time2; if(ExtendZones) time2 = Time[0] + (Time[0] - Time[1]) * 20; // Extend to the right else time2 = Time[0]; // Just to current bar double price1 = g_Zones[i].high; double price2 = g_Zones[i].low; // Make sure the rectangle is created if(!ObjectCreate(0, objName, OBJ_RECTANGLE, 0, time1, price1, time2, price2)) { Print("Failed to create zone rectangle: ", GetLastError()); continue; } // Set rectangle properties ObjectSetInteger(0, objName, OBJPROP_COLOR, zoneColor); ObjectSetInteger(0, objName, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, objName, OBJPROP_WIDTH, 1); ObjectSetInteger(0, objName, OBJPROP_FILL, true); ObjectSetInteger(0, objName, OBJPROP_BACK, true); // For MQL4 we use color with alpha component // Calculate color with opacity color fillColor = ColorToARGB(zoneColor, ZoneOpacity); ObjectSetInteger(0, objName, OBJPROP_BGCOLOR, fillColor); // Add label with strength string labelName = "Label_" + objName; string labelText = g_Zones[i].isSupply ? "Supply" : "Demand"; labelText += " (" + DoubleToString(g_Zones[i].strength, 1) + ")"; if(!ObjectCreate(0, labelName, OBJ_TEXT, 0, time1, g_Zones[i].isSupply ? price1 : price2)) { Print("Failed to create label: ", GetLastError()); continue; } ObjectSetString(0, labelName, OBJPROP_TEXT, labelText); ObjectSetInteger(0, labelName, OBJPROP_COLOR, zoneColor); ObjectSetInteger(0, labelName, OBJPROP_FONTSIZE, 8); } // Force chart redraw ChartRedraw(); } //+------------------------------------------------------------------+ //| Convert color to ARGB format with alpha | //+------------------------------------------------------------------+ color ColorToARGB(color clr, uchar alpha) { // Extract RGB components uchar r = (uchar)clr; uchar g = (uchar)(clr >> 8); uchar b = (uchar)(clr >> 16); // Create new color with alpha return(color)((alpha << 24) + (b << 16) + (g << 8) + r); } //+------------------------------------------------------------------+ //| Delete all zone objects | //+------------------------------------------------------------------+ void DeleteAllZones() { int total = ObjectsTotal(); for(int i = total - 1; i >= 0; i--) { string objName = ObjectName(i); if(StringFind(objName, "SupplyZone_") >= 0 || StringFind(objName, "DemandZone_") >= 0 || StringFind(objName, "Label_") >= 0) { ObjectDelete(objName); } } } //+------------------------------------------------------------------+I've made several important changes to fix the issue with zones not displaying:
- Simplified the zone identification criteria to make it more likely to identify zones
- Fixed an issue with the ZoneStrength parameter (set to 1 by default now)
- Added a proper ColorToARGB function to handle transparency in MQL4
- Added error checking and debugging messages to help identify problems
- Fixed the zone drawing code to ensure objects are properly created
- Changed to use tick_volume instead of volume as it's always available
- Added ChartRedraw() to force the chart to update after drawing
- Fixed several logical errors in the code
Try this revised version. If you're still not seeing zones, check the Experts tab in MT4 for any error messages, and consider adjusting the parameters (especially LookBack and VolumeFactor) to make zone identification less strict.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.