Problem Description
Solution
Here is a complete, ready-to-use MQL4 script.
Script Logic
- Inputs: Allows you to change the number of bars to scan (default is 50) and the color of the Fibonacci lines.
- High/Low Search: It uses
iHighestandiLowestto find the highest and lowest price points within the specified range. - Trend Detection: It compares the time (index) of the High versus the Low.
- If the Low is older (higher index) than the High, it identifies an Uptrend and draws from Low to High.
- If the High is older than the Low, it identifies a Downtrend and draws from High to Low.
- Drawing: Creates an
OBJ_FIBOobject and sets visual properties.
MQL4 Code
//+------------------------------------------------------------------+
//| AutoFibo50.mq4 |
//| Copyright 2023, MetaQuotes |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, Quantitative Assistant"
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
#property script_show_inputs
//--- Input Parameters
input int InpBarsToScan = 50; // Number of bars to look back
input color InpFiboColor = clrGold; // Color of the Fibo lines
input bool InpRayRight = true; // Extend lines to the right
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// 1. Validate inputs
if(InpBarsToScan <= 1)
{
Alert("Please specify at least 2 bars to scan.");
return;
}
// 2. Find the Highest and Lowest bar indices in the range
// We scan from index 0 (current bar) back to InpBarsToScan
int highestIndex = iHighest(Symbol(), Period(), MODE_HIGH, InpBarsToScan, 0);
int lowestIndex = iLowest(Symbol(), Period(), MODE_LOW, InpBarsToScan, 0);
// Check for errors in retrieving data
if(highestIndex == -1 || lowestIndex == -1)
{
Print("Error retrieving High/Low data. Error code: ", GetLastError());
return;
}
// 3. Get the Price and Time coordinates
double priceHigh = iHigh(Symbol(), Period(), highestIndex);
double priceLow = iLow(Symbol(), Period(), lowestIndex);
datetime timeHigh = iTime(Symbol(), Period(), highestIndex);
datetime timeLow = iTime(Symbol(), Period(), lowestIndex);
// 4. Define Object Name
string objName = "AutoFibo_Last" + IntegerToString(InpBarsToScan);
// 5. Delete existing object with the same name to avoid conflicts/duplicates
if(ObjectFind(0, objName) >= 0)
{
ObjectDelete(0, objName);
}
// 6. Create the Fibonacci Object
// Logic: We draw from the "Older" point to the "Newer" point to respect the trend direction.
// Note: In MQL4, Index 50 is older (further back in time) than Index 0.
bool created = false;
if(highestIndex > lowestIndex)
{
// The High happened BEFORE the Low (High index is larger).
// This indicates a DOWNTREND move.
// Anchor 1 = High, Anchor 2 = Low.
created = ObjectCreate(0, objName, OBJ_FIBO, 0, timeHigh, priceHigh, timeLow, priceLow);
}
else
{
// The Low happened BEFORE the High (Low index is larger).
// This indicates an UPTREND move.
// Anchor 1 = Low, Anchor 2 = High.
created = ObjectCreate(0, objName, OBJ_FIBO, 0, timeLow, priceLow, timeHigh, priceHigh);
}
// 7. Set Properties if creation was successful
if(created)
{
ObjectSetInteger(0, objName, OBJPROP_COLOR, InpFiboColor);
ObjectSetInteger(0, objName, OBJPROP_RAY_RIGHT, InpRayRight);
ObjectSetInteger(0, objName, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, objName, OBJPROP_STYLE, STYLE_SOLID);
// Optional: Select the object so you can modify it manually immediately
ObjectSetInteger(0, objName, OBJPROP_SELECTABLE, true);
ObjectSetInteger(0, objName, OBJPROP_SELECTED, true);
// Force chart redraw to show object immediately
ChartRedraw(0);
}
else
{
Print("Failed to create Fibo object. Error code: ", GetLastError());
}
}
//+------------------------------------------------------------------+
How to install and use:
- Open MetaTrader 4.
- Press
F4to open the MetaEditor. - In the Navigator panel (left side), right-click on the Scripts folder and select New File.
- Select Script, name it
AutoFibo50, and click Finish. - Delete everything in the new window and paste the code above.
- Press
F7to Compile. - Go back to the main MT4 window.
- Drag
AutoFibo50from the Scripts section onto any chart.
Q&A
Q: How does the script decide which direction to draw the Fibonacci?
A: The script compares the bar index of the highest high and the lowest low. In MT4, a higher index means the bar is older (further to the left).
- If
High_Index > Low_Index, the High happened before the Low. This is a downward move, so the Fibo is drawn from Top (100%) to Bottom (0%). - If
Low_Index > High_Index, the Low happened before the High. This is an upward move, so the Fibo is drawn from Bottom (100%) to Top (0%).
Q: Will this update automatically as price moves?
A: No, this is a Script, not an Indicator or Expert Advisor. Scripts run once and then stop. If you want the Fibo to update dynamically with every new tick, this code would need to be converted into a Custom Indicator or EA running inside OnTick() or OnCalculate().
Q: Can I change the number of bars without editing the code?
A: Yes. When you drag the script onto the chart, a window will pop up (because of #property script_show_inputs). You can change InpBarsToScan from 50 to any number you prefer.