Fibonacci Extension Levels Indicator for MT5

Author: Roberto Jacobs (3rjfx)

Master the Fibonacci Extension Levels Indicator for MT5. Enhance your Forex Analysis, Price Action, and Day Trading with this powerful tool.

Introduction

Welcome to Forex Home Expert, your premier and most trusted destination for mastering the intricate, dynamic, and highly rewarding world of the global foreign exchange market. In the highly competitive, fast-paced, and often unforgiving realm of Technical analysis, possessing the right, professionally developed Trading Tools can fundamentally and permanently transform your analytical approach.
This transformation makes the critical, account-saving difference between achieving consistent, sustainable, long-term profitability and suffering from frustrating, unpredictable, and emotionally draining losses. Today, we are diving exceptionally deep into a powerful, custom-built, and meticulously engineered MetaTrader 5 (MT5) indicator: the Fibonacci Extension Levels Indicator.
Meticulously designed from the ground up for serious traders who demand absolute precision, clarity, and reliability, this innovative tool automates the historically complex, subjective, and time-consuming process of plotting Fibonacci extension levels directly onto your live, ticking price charts.
Whether you are actively engaged in high-frequency, scalping-oriented Day Trading or conducting comprehensive, macroeconomic, long-term Forex Analysis, understanding the underlying, fractal market structure is absolutely paramount to your enduring success.
The Fibonacci sequence, discovered by the Italian mathematician Leonardo of Pisa, has served as a foundational, unshakeable cornerstone of Price Action trading for many decades. It provides a profound sense of mathematical harmony, natural proportion, and predictable structure to seemingly chaotic, random market movements.
By accurately identifying potential reversal zones, exhaustion points, and logical profit targets that extend far beyond the standard 100% retracement levels, this indicator empowers both retail and institutional traders alike to anticipate market exhaustion, capitalize on precise Momentum Detection, and execute trades with unwavering, data-driven confidence.
In this comprehensive, deeply analytical, and extensively detailed article, we will meticulously dissect the MQL5 source code of the Fibonacci Extension Levels Indicator.
We will thoroughly explore its underlying object-oriented architecture, its core computational functions, and its practical, real-world applications in live market conditions.
By the conclusion of this extensive guide, you will not only understand exactly how to deploy this indicator effectively within your own unique trading environment, but you will also deeply appreciate the sophisticated, professional-grade programming logic that drives its seamless, high-performance operation.
Let us embark on this educational journey to significantly elevate your overall Trading strategy and refine your innate ability to generate high-probability, reliable trading signals in any market condition, across any asset class.

What is the Fibonacci Extension Levels Indicator?

The Fibonacci Extension Levels 0 ~ 261 indicator is an advanced technical analysis tool designed to help traders project potential price targets following a market retracement. Unlike standard Fibonacci Retracement tools that measure how deep a temporary pullback goes, Fibonacci Extensions look forward—calculating how far the ensuing impulse wave will travel.

In this custom MQL5 version, the indicator comes equipped with high-level automation features:

  1. Extended Range Levels: Maps positive extension levels from $0.0$ to $261.8$ (`LvlExp[]={0.0, 11.8, 23.6, 38.2, 50.0, 61.8, 76.4, 88.2, 100.0, 111.8, 123.6, 138.2, 150.0, 161.8, 176.4, 188.2, 200.0, 211.8, 223.6, 238.2, 250.0, 261.8}`) alongside negative levels for reciprocal directional projections.
  2. Keyboard-Controlled Interactive Panel: Allows traders to show or hide the price level panel instantly on the chart without cluttering the workspace.
  3. Clean Professional Visuals: Automated trendlines, custom price labels, and neatly organized level markers ensure your analysis remains sharp and free of visual noise.
Fibonacci Extension Levels 0 ~ 261
Figure 1: Fibonacci Extension Levels 0 ~ 261

1. Decoding Global Variables and Input Properties

The absolute foundation of any robust, professional-grade MetaTrader 5 indicator lies in its configuration flexibility and user-centric design, and this Fibonacci Extension Levels Indicator is absolutely no exception to this golden rule.
The source code begins by defining a comprehensive series of global variables and input properties that allow traders to seamlessly tailor the visual and functional aspects of the tool to their specific, individualized Forex Strategy. At the very top of the script, we see the standard, yet essential, MQL5 property declarations. These include copyright information, versioning details, and a clear, descriptive explanation of the indicator’s primary purpose: plotting Fibonacci Extension Levels ranging from 0.0% all the way up to 261.8%.
A particularly user-friendly, innovative feature is prominently highlighted in these property descriptions: the ability to activate or completely remove the price level information panel simply by left-clicking anywhere on the chart and pressing the KEY_UP or KEY_DOWN keyboard buttons.
This intuitive, keyboard-driven design philosophy ensures that even novice traders can navigate, control, and utilize the tool effectively without feeling overwhelmed by complex, multi-layered dropdown menus or hidden settings.

Delving deeper into the specific input parameters, the code introduces a custom, strongly-typed enumeration named YN, which elegantly stands for "Yes" or "No". This enumeration is strategically utilized for the cshift variable, which directly controls the "Auto shift and Auto scroll chart" functionality.
When this parameter is explicitly set to "Yes", the indicator dynamically and automatically adjusts the chart view to ensure that all newly calculated extension levels remain perfectly visible within the viewport. This is a crucial, often overlooked feature for maintaining optimal situational awareness during highly volatile, news-driven market sessions.
Following this, a comprehensive series of color inputs are defined to allow complete customization of the visual presentation. Variables such as trenclr (Trend Line Color, defaulting to a highly visible gold), labelclr (Fibonacci Value Color, defaulting to a crisp snow white), endclr (End of Trend Lines Color, defaulting to a distinct deep pink), labelprc (Price Value Color), trncross (Trend Line Cross Color, defaulting to an alerting red), and cntcross (Center Cross Color, defaulting to a calming aqua) provide granular, pixel-level control over the chart’s aesthetics.
This extensive level of visual customization is absolutely vital for professional traders who rely on clean, uncluttered, and color-coded charts to maintain intense focus during demanding Day Trading sessions.

Furthermore, the core mathematical foundation of the entire indicator is firmly established through two distinct, double-precision floating-point arrays: Lvl and LvlExp.
The Lvl array contains the standard, widely recognized Fibonacci retracement and extension percentages (0.0, 11.8, 23.6, 38.2, 50.0, 61.8, 76.4, 88.2, 100.0).
In contrast, the LvlExp array extends this mathematical sequence significantly further, reaching ambitious targets up to 261.8%.
These extended levels are particularly valuable and highly sought after for identifying aggressive profit targets in strong, unidirectional trending markets, where price action frequently and forcefully overshoots the traditional 100% or 161.8% marks.
Finally, the code defines critical, hardcoded constants such as BAR_LIMIT (strategically set to 100), which dictates the minimum number of historical bars required for accurate, statistically significant calculation. It also defines the keyboard key codes KEY_UP (38) and KEY_DOWN (40), which are later utilized in the event-handling functions to seamlessly toggle the user interface panel on and off.


//+------------------------------------------------------------------+
//|                                   Fibonacci Extension Levels.mq5 |
//|        Copyright 2026, Roberto Jacobs (3rjfx) ~ Date: 2026-10-27 |
//|                              https://www.mql5.com/en/users/3rjfx |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Roberto Jacobs (3rjfx) ~ Date: 2026-10-27"
#property link      "https://www.mql5.com/en/users/3rjfx"
#property link      "https://www.forexhomeexpert.com/"
#property version   "1.00"
#property strict
#property description "Fibonacci Extension Levels 0 ~ 261"
#property description "To activate the price level panel, left click on the chart and PRESS the KEY_UP keyboard."
#property description "To remove the price level panel, left click on the chart and PRESS the KEY_DOWN keyboard."
#property description "version: 1.00 ~ Last update 2026/10/27 @ 15:51 PM WIT (Western Indonesian Time)"
//---
#property indicator_chart_window
#property indicator_plots  0
//--
//---
enum YN
 {
   No,  // No
   Yes  // Yes
 };
//--
//---
input YN                cshift = Yes;           // Auto shift and Auto scroll chart (Yes) or (No)
input color            trenclr = clrGold;       // Colors for Trend Lines
input color           labelclr = clrSnow;       // Colors for Fibonacci Value
input color             endclr = clrDeepPink;   // Colors for End of Trend Lines
input color           labelprc = clrSnow;       // Colors for Price Value
input color           trncross = clrRed;        // Colors for Trend Line Cross
input color           cntcross = clrAqua;       // Colors for Trend Line Cross
//---
double 
  Lvl[]={0.0,11.8,23.6,38.2,50.0,61.8,76.4,88.2,100.0},
  LvlExp[]={0.0,11.8,23.6,38.2,50.0,61.8,76.4,88.2,100.0,111.8,123.6,138.2,150.0,161.8,176.4,188.2,200.0,211.8,223.6,238.2,250.0,261.8};
//----
//--- bars minimum for calculation
#define BAR_LIMIT  100
#define KEY_UP     38 
#define KEY_DOWN   40 
//---------//
***Copyright © 2026 3rjfx ~ For educational purposes only.***

2. The Heart of the Code: Class FiboExtension

To ensure maximum modularity, long-term maintainability, and professional-grade code structure, we has intelligently encapsulated the core computational logic within a dedicated, object-oriented class named FiboExtension.
This object-oriented programming (OOP) approach is a definitive hallmark of advanced, enterprise-level MQL5 development. It effectively prevents global variable name collisions, reduces memory leaks, and organizes related data and functions into a single, cohesive, and easily manageable unit.
The class begins by declaring private integer variables dedicated exclusively to precise time management, such as x_year, x_mon, x_day, x_hour, x_min, and x_sec.
These variables are absolutely essential for accurately timestamping drawn objects and ensuring that the indicator’s complex calculations are perfectly synchronized with the broker’s server time, which is a critical, non-negotiable factor in accurate, reliable Forex Analysis.

In the public section of the class, we find the core computational variables that directly drive the Fibonacci mathematics.
The variable hldif represents the high-low price difference, calculated by subtracting the minimum low from the maximum high over a specified, user-defined period.
The GrLvl (Grid Level) variable represents the precise monetary value of a single grid step, derived by dividing the hldif by the 100% level value.
The maxHi and minLo variables store the absolute highest high and lowest low prices identified within the active calculation window, serving as the foundational anchor points for all subsequent Fibonacci projections.
Additionally, the class includes spatial positioning variables like xdis and ydis for precise panel placement, and a boolean flag dispp to efficiently track whether the information panel is currently displayed on the chart, preventing redundant rendering cycles.

The class also houses several specialized, highly optimized methods designed to handle time-related operations with absolute precision.
The ReqTime function extracts specific temporal components (year, month, day, hour, minute, second, day of week, or day of year) from a given datetime object, allowing for highly granular, time-based filtering or detailed logging.
Similarly, the ThisTime function retrieves the current server time components, ensuring that any newly drawn chart objects are accurately and consistently timestamped.
The timehr and ReqDate methods work in perfect tandem to format these raw time components into clean, human-readable strings, which can be used for labeling chart objects or generating detailed, auditable log entries.
By centralizing these crucial time-management functions within the FiboExtension class, the code remains remarkably clean, highly efficient, and exceptionally resistant to runtime errors, providing a rock-solid foundation for real-time Momentum Detection and flawless chart rendering.


class FiboExtension
  {
//---
    private:
    //--
    int             x_year; // Year 
    int             x_mon;  // Month 
    int             x_day;  // Day of the month 
    int             x_hour; // Hour in a day 
    int             x_min;  // Minutes 
    int             x_sec;  // Seconds
    //---
    

    public:
    //--
                    FiboExtension(void);
                    ~FiboExtension(void);
    
    //--
    double          hldif,
                    GrLvl,
                    maxHi,
                    minLo;
    //--
    int             xdis,
                    ydis;
    int             ArLX,
                    hilo;
    int             csec,
                    psec;
    
    
    //--
    int             year,   // Year 
                    mon,    // Month 
                    day,    // Day 
                    hour,   // Hour 
                    min,    // Minutes 
                    sec,    // Seconds 
                    dow,    // Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) 
                    doy;    // Day number of the year (January 1st is assigned the number value of zero)
    //--
    long            ChId;
    //--
    string          indiname;
    string          fbpanl;
    string          fbtext;
    //--
    color           txtnormal;
    //--
    bool            dispp;
    //--
    int             ReqTime(datetime reqtime,const int reqmode);
    int             ThisTime(const int reqmode);
    //--
    string          timehr(int hr,int mn);
    string          ReqDate(int d,int h,int m);    
    //------------
//---
  }; //-end class FiboExtension
//---------//
    
FiboExtension fex;

***Copyright © 2026 3rjfx ~ For educational purposes only.***

3. Dynamic Market Processing and Advanced Object Creation

The true, dynamic intelligence of the Fibonacci Extension Levels Indicator is activated and sustained within the OnCalculate function, which is automatically triggered every single time a new tick of live market data is received by the terminal.
This function is heavily responsible for processing the incoming, multi-dimensional price arrays (open, high, low, close, time, tick volume, volume, and spread) and dynamically updating the chart objects in real-time.
The function first performs a vital, fail-safe safety check: if the rates_total (the total number of available bars on the chart) is less than the predefined BAR_LIMIT of 100, the function immediately returns zero.
This prevents erroneous, misleading calculations on insufficient, statistically insignificant data. If the cshift input is enabled, the function programmatically toggles the chart’s auto-scroll and shift properties, ensuring the most recent, actionable price action remains perfectly framed within the trader’s active view.

Following the initial setup, the code employs the ArraySetAsSeries function to reverse the indexing of the price arrays, ensuring that the most recent, active bar is always located at index zero.
This is a standard, absolutely crucial practice in MQL5 for accurate, backward-looking technical calculations.
The indicator then identifies the maxHi and minLo over the specified hilo period. With these critical anchor points firmly established, it calculates the hldif and subsequently the GrLvl.
The core rendering logic is elegantly wrapped in a time-based condition: if(fex.csec != fex.psec).
This brilliant optimization ensures that the computationally intensive task of drawing or updating chart objects only occurs exactly once per second.
This drastically reduces CPU usage and prevents terminal lag, which is especially important and noticeable during high-volatility, high-impact news events.

Inside this optimized conditional block, the code utilizes a comprehensive suite of dedicated, highly reusable functions designed to create, manage, and destroy various MetaTrader 5 chart objects efficiently.
The CreateTrendLine function draws the horizontal Fibonacci levels, accepting parameters for chart ID, object name, times, price levels, width, style, color, and ray properties, while proactively calling ObjectDelete to prevent duplicate objects.
Similarly, the CreateText function places descriptive labels at the right edge of the chart using professional fonts, and the CreateArrPrice function generates right-pointing price arrows directly on the price axis for immediate reference.
The crown jewel of this visual system is the CreateFiboExPanel function, which constructs a comprehensive, neatly organized dashboard in the corner of the chart.
It utilizes the CreateButtonTemplate function and a custom WS (Width Scaling) function that queries the terminal’s screen DPI to ensure the panel appears crisp and perfectly proportionate on both high-resolution 4K monitors and standard displays.
Complementing this is the OnChartEvent function, which listens for the CHARTEVENT_KEYDOWN event. Pressing KEY_UP invokes the panel creation, while pressing KEY_DOWN securely deletes the panel objects, providing instant, on-demand access to critical analytical data without permanently cluttering the chart.


//+------------------------------------------------------------------+
//| 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[])
  {
//---
//--- Set Last error value to Zero
   ResetLastError();
//--- check for rates total
   if(rates_total<BAR_LIMIT)
      return(0);
   //--
   if(cshift==Yes)
     {
       if(ChartSetInteger(fex.ChId,CHART_AUTOSCROLL,0,false))
          ChartSetInteger(fex.ChId,CHART_AUTOSCROLL,0,true);
       if(ChartSetInteger(fex.ChId,CHART_SHIFT,0,false))
          ChartSetInteger(fex.ChId,CHART_SHIFT,0,true);
     }
   //--
   fex.hilo=BAR_LIMIT;
   //--
   ArraySetAsSeries(open,true);
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true);
   ArraySetAsSeries(close,true);
   ArraySetAsSeries(time,true);
//----
   int Alvl=ArraySize(Lvl);
   fex.ArLX=ArraySize(LvlExp);
   int Alvt=Alvl-1;
   double Lvl100=Lvl[Alvt];
   int cross=int(Alvl/2);
   int crosm=3;
   int f=0;
   fex.maxHi=0;
   fex.minLo=0;
   datetime Cor1,Cor2,CorC,CorL;
   Cor1=time[0];
   Cor2=time[70];
   CorL=time[71];
   CorC=time[35];
   fex.minLo=low[ArrayMinimum(low,0,fex.hilo)];
   fex.maxHi=high[ArrayMaximum(high,0,fex.hilo)];
   fex.hldif=NormalizeDouble(fex.maxHi-fex.minLo,Digits());
   fex.GrLvl=NormalizeDouble(fex.hldif/Lvl100,Digits());
   //--
//----- Time to create the Fibonacci object
   fex.csec=fex.ThisTime(fex.sec);
   //---
   if(fex.csec!=fex.psec)
     {
       if(!fex.dispp)
         {
           for(f=0; f<fex.ArLX; f++)
             {
               CreateTrendLine(fex.ChId,fex.fbtext+"LineLevels_"+string(f),Cor1,fex.minLo+(fex.GrLvl*LvlExp[f]),Cor2,
                               fex.minLo+(fex.GrLvl*LvlExp[f]),1,STYLE_DASHDOT,trenclr,false,true);
               CreateText(fex.ChId,fex.fbtext+"Labels_"+string(f),CorL,fex.minLo+(fex.GrLvl*LvlExp[f]),
                          DoubleToString(LvlExp[f],1),"Bodoni MT Black",8,labelclr,ANCHOR_RIGHT);
               CreateText(fex.ChId,fex.fbtext+"Limit_"+string(f),Cor2,fex.minLo+(fex.GrLvl*LvlExp[f]),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER);
               CreateArrPrice(fex.ChId,fex.fbtext+"LabelPrice_"+string(f),Cor2,fex.minLo+(fex.GrLvl*LvlExp[f]),1,clrSnow,STYLE_SOLID,ANCHOR_LEFT);
               CreateChannel(fex.ChId,fex.fbtext+"LineCross1",Cor2,Cor1,fex.minLo+(fex.GrLvl*Lvl100),fex.minLo+(fex.GrLvl*Lvl[0]),trncross,STYLE_DOT,false);
               CreateChannel(fex.ChId,fex.fbtext+"LineCross2",Cor2,Cor1,fex.minLo+(fex.GrLvl*Lvl[0]),fex.minLo+(fex.GrLvl*Lvl100),trncross,STYLE_DOT,false);
               CreateText(fex.ChId,fex.fbtext+"LineLimit6",Cor1,fex.minLo+(fex.GrLvl*Lvl[0]),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER);
               CreateText(fex.ChId,fex.fbtext+"LineLimit0",Cor1,fex.minLo+(fex.GrLvl*Lvl[Alvt]),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER); 
               CreateText(fex.ChId,fex.fbtext+"StarCross",CorC,fex.minLo+(fex.GrLvl*Lvl[cross]),CharToString(181),"Wingdings",15,cntcross,ANCHOR_CENTER);
             }
           //--
           for(int x=1; x<fex.ArLX; x++)
             {
               CreateTrendLine(fex.ChId,fex.fbtext+"LineLevels_m"+string(x),Cor1,fex.minLo+(-fex.GrLvl*LvlExp[x]),Cor2,
                               fex.minLo+(-fex.GrLvl*LvlExp[x]),1,STYLE_DASHDOT,trenclr,false,true);
               CreateText(fex.ChId,fex.fbtext+"Labels_m"+string(x),CorL,fex.minLo+(-fex.GrLvl*LvlExp[x]),
                          "-"+DoubleToString(LvlExp[x],1),"Bodoni MT Black",8,labelclr,ANCHOR_RIGHT);
               CreateText(fex.ChId,fex.fbtext+"Limit_m"+string(x),Cor2,fex.minLo+(-fex.GrLvl*LvlExp[x]),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER);
               CreateArrPrice(fex.ChId,fex.fbtext+"LabelPrice_m"+string(x),Cor2,fex.minLo+(-fex.GrLvl*LvlExp[x]),1,clrSnow,STYLE_SOLID,ANCHOR_LEFT);
               CreateChannel(fex.ChId,fex.fbtext+"LineCross1m",Cor2,Cor1,fex.minLo+(-fex.GrLvl*Lvl100),fex.minLo+(-fex.GrLvl*Lvl[0]),trncross,STYLE_DOT,false);
               CreateChannel(fex.ChId,fex.fbtext+"LineCross2m",Cor2,Cor1,fex.minLo+(-fex.GrLvl*Lvl[0]),fex.minLo+(-fex.GrLvl*Lvl100),trncross,STYLE_DOT,false);
               CreateText(fex.ChId,fex.fbtext+"LineLimit0m",Cor1,fex.minLo+(-fex.GrLvl*Lvl100),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER); 
               CreateText(fex.ChId,fex.fbtext+"StarCrossm",CorC,fex.minLo+(-fex.GrLvl*LvlExp[crosm]),CharToString(181),"Wingdings",15,cntcross,ANCHOR_CENTER);
             }
           //--
         }
       //--
       fex.psec=fex.csec;
       if(fex.dispp) CreateFiboExPanel();
     }
   //---
   ChartRedraw(fex.ChId);
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
***Copyright © 2026 3rjfx ~ For educational purposes only.***

4. Practical Application in Modern Trading Strategies

Understanding the underlying code is only half the battle; applying it effectively in live market conditions is where true, consistent profitability is forged.
The Fibonacci Extension Levels Indicator is exceptionally versatile, catering to a wide, diverse array of trading methodologies and styles. For dedicated practitioners of Price Action trading, this tool is absolutely invaluable for identifying precise, high-reward take-profit zones.
After a clear, strong impulse move and a subsequent, healthy retracement to a key support or resistance level (such as the 61.8% or 78.6% retracement), traders can confidently use the extension levels (127.2%, 161.8%, and 261.8%) to set logical, mathematically sound profit targets.
This systematic approach completely removes emotional guesswork from the equation, allowing for disciplined, rules-based trade management.

In the fast-paced realm of Day Trading, where speed, precision, and execution are paramount, the indicator’s ability to instantly calculate and display these levels upon chart attachment saves crucial, valuable seconds.
Instead of manually dragging a standard Fibonacci tool and painstakingly adjusting its anchors to the exact wicks, the indicator automatically identifies the recent high and low, instantly projecting the levels with mathematical perfection.
This automation is particularly beneficial during intense Momentum Detection phases, such as the opening of the London or New York sessions, where rapid, explosive price movements require immediate, reliable analytical support.
Furthermore, the extended levels up to 261.8% are highly effective in strong, trending markets or during major breakout scenarios, where traditional, conservative targets are frequently and forcefully exceeded.
By combining this indicator with other, complementary forms of Forex Analysis, such as volume profile, order flow, or candlestick pattern recognition, traders can effectively filter out false breakouts and focus exclusively on high-confluence, high-probability setups.
Ultimately, this indicator transforms abstract, theoretical mathematical ratios into highly actionable trading signals, providing a structured, reliable framework that enhances any robust, well-tested Trading strategy.

How to Use the Fibonacci Extension Levels Indicator in MT5

To make the most of this indicator in your daily trading routine, follow these practical operating guidelines:

A. Installation and Panel Activation (Keyboard Shortcuts)

Once the indicator is attached to your MetaTrader 5 chart, you can control the visibility of the price information panel using simple keyboard strokes:

  1. Displaying the Price Panel: Left-click anywhere on the chart and PRESS the KEY_UP keyboard button. A detailed information panel listing all levels from 0 to 261 will appear in the upper-right corner of your screen.
  2. Hiding the Price Panel: Left-click on the chart and PRESS the KEY_DOWN keyboard button to clear the panel whenever you want an uncluttered view of your candlesticks.

B. Reading Key Levels for Take Profit (TP)

The indicator automatically calculates the highest high (`maxHi`) and lowest low (`minLo`) within a minimum threshold of the last 100 bars (`BAR_LIMIT 100`), dynamically projecting Fibonacci ratios:

  1. Levels 100.0 to 161.8 (Primary Target Zone): The golden extension pocket where institutional traders often begin scaling out of positions. The 161.8 level is a classic, highly reliable target during strong trends.
  2. Levels 200.0 to 261.8 (Maximum Extension Zone): Utilized during aggressive market momentum (strong impulse trends). When prices breach 200.0 and push toward 261.8, market momentum is at its peak.
  3. Negative Levels (`Level -`): Help map price expansion projections in the opposite direction if a sudden market reversal occurs within the reference range.

C. Automatic Chart Adjustments (Auto Shift & Scroll)

Through the input parameter setting `cshift = Yes`, the indicator automatically enables auto-scroll and chart-shift functions on your MT5 platform. This ensures that blank space is always preserved on the right edge of your chart, keeping your Fibonacci projection lines fully visible and unclipped.

Frequently Asked Questions (FAQ)

Q: How do I install the Fibonacci Extension Levels Indicator on my MT5 platform?

A: The installation process is straightforward and user-friendly. Simply download the compiled .ex5 file or the source .mq5 file. Open your MT5 platform, navigate to 'File' > 'Open Data Folder', and place the file directly into the MQL5/Indicators directory. Restart your MT5 platform or refresh the Navigator panel, then drag and drop the indicator onto your desired chart.

Q: Can I customize the Fibonacci levels to match my specific trading preferences?

A: Yes, absolutely. While the source code comes pre-configured with standard and extended levels (up to 261.8%), advanced users who possess basic MQL5 knowledge and compile the code can easily modify the Lvl and LvlExp arrays in the source code. You can add or remove custom ratios, such as 78.6% or 382%, to perfectly align with your unique, personalized Forex Strategy.

Q: Does this indicator work on all timeframes and currency pairs?

A: Yes, the indicator is completely timeframe and symbol agnostic. Whether you are analyzing the 1-minute chart for rapid scalping or the daily chart for long-term swing trading, the underlying logic automatically adapts to the available price data. This makes it a universally applicable Technical analysis tool across all Forex pairs, major indices, and commodity markets.

Q: What should I do if the indicator does not draw the levels correctly?

A: Ensure that your chart has at least 100 bars of historical data loaded, as dictated by the BAR_LIMIT constant. If the issue persists, try removing the indicator, restarting the MT5 terminal, and reapplying it. Also, verify that the 'Auto shift and Auto scroll chart' input is set to 'Yes' to ensure the chart view adjusts properly.

Conclusion

In conclusion, the Fibonacci Extension Levels Indicator for MT5 represents a masterful, seamless blend of timeless mathematical precision and sophisticated, modern MQL5 programming.
By automating the complex calculation and crisp visualization of critical extension levels, it completely eliminates manual measurement errors and saves valuable, critical time, allowing traders to focus entirely on market dynamics, risk management, and flawless execution.
From its highly customizable input properties and robust, object-oriented class structure to its efficient, CPU-friendly event handling and DPI-aware visual rendering, every single aspect of this indicator has been meticulously crafted to serve the demands of the modern, discerning trader.
Whether you are actively refining your Price Action methodology, seeking enhanced, reliable Momentum Detection, or simply looking to add a dependable, professional-grade instrument to your comprehensive suite of Trading Tools, this indicator delivers exceptional, measurable value.
We strongly encourage you to download, thoroughly test, and seamlessly integrate this powerful tool into your daily Forex Analysis routine.
By doing so, you will be significantly better equipped to identify high-probability trading signals, manage your risk effectively, and ultimately elevate your overall Trading strategy to new, unprecedented heights of consistency and profitability.
Welcome to a smarter, more precise, and more profitable way of trading with Forex Home Expert.

The Fibonacci Extension Levels 0 ~ 261 indicator is more than just a set of regular drawing lines—it is a structured mathematical system that brings institutional-grade precision to your MetaTrader 5 platform.
Use its key levels to lock in profits systematically and take emotion out of your trading decisions.

Vital Records

We hope that this article and the Fibonacci Extension Levels - Indicator for MT5 program will be useful for traders in learning and generating new ideas, thereby will be able improving your trading performance.

We hope you find our content useful and thank you for visiting the Forex Home Expert.

See you in the next article on Expert Advisor programs or indicators for MetaTrader 4, MetaTrader 5 or Python program and trading psychology.

Explore more algorithmic trading resources:

Note: This program is shared under a Copyleft/Creative Commons License (CCL) for educational purposes. There is no direct download link available. Before obtaining the source code, if you wish to support our algorithmic trading operations, you can check out something interesting for you. Then, please follow the detailed steps below to manually install it in your MQL4/MQL5 MetaEditor.

πŸ“‹ How to Install This Program (Manual Copy-Paste Guide)

Step-by-Step Instructions:

  1. Open your MQL5 MetaEditor (press F4 in MT5).
  2. Click "New" (or File > New) to create a new document.
  3. Select the program type:
    • Choose Expert Advisor (template) if this is an EA.
    • Choose Custom Indicator if this is an indicator.
  4. Enter the Name (e.g., ECN) and click "Next" twice.
  5. Click "Finish". A blank template page will be created.
  6. Scroll down and click the "Full Source Code Preview (CCL)" button below.
  7. Click the View Code button at the bottom left, and click the Copy Code button at the top right.
  8. Return to the blank MetaEditor page, Paste the code (Ctrl+V), replacing any default text.
  9. Click "Compile" (F7). Check the Toolbox panel: if there are 0 errors, your program is ready!

Summary: This section provides a manual copy-paste installation guide for MQL4/MQL5 Expert Advisors and Custom Indicators shared under CCL license. Users must open MetaEditor, create a new file, copy the source code from the preview section below, paste it into the editor, and compile the program to use it on MetaTrader 4/5 charts.

☕ Support the Developer: Click here to view something interesting for you..


//+------------------------------------------------------------------+
//|                                   Fibonacci Extension Levels.mq5 |
//|        Copyright 2026, Roberto Jacobs (3rjfx) ~ Date: 2026-10-27 |
//|                              https://www.mql5.com/en/users/3rjfx |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Roberto Jacobs (3rjfx) ~ Date: 2026-10-27"
#property link      "https://www.mql5.com/en/users/3rjfx"
#property link      "https://www.forexhomeexpert.com/"
#property version   "1.00"
#property strict
#property description "Fibonacci Extension Levels 0 ~ 261"
#property description "To activate the price level panel, left click on the chart and PRESS the KEY_UP keyboard."
#property description "To remove the price level panel, left click on the chart and PRESS the KEY_DOWN keyboard."
#property description "version: 1.00 ~ Last update 2026/10/27 @ 15:51 PM WIT (Western Indonesian Time)"
//---
#property indicator_chart_window
#property indicator_plots  0
//--
//---
enum YN
 {
   No,  // No
   Yes  // Yes
 };
//--
//---
input YN                cshift = Yes;           // Auto shift and Auto scroll chart (Yes) or (No)
input color            trenclr = clrGold;       // Colors for Trend Lines
input color           labelclr = clrSnow;       // Colors for Fibonacci Value
input color             endclr = clrDeepPink;   // Colors for End of Trend Lines
input color           labelprc = clrSnow;       // Colors for Price Value
input color           trncross = clrRed;        // Colors for Trend Line Cross
input color           cntcross = clrAqua;       // Colors for Trend Line Cross
//---
double 
  Lvl[]={0.0,11.8,23.6,38.2,50.0,61.8,76.4,88.2,100.0},
  LvlExp[]={0.0,11.8,23.6,38.2,50.0,61.8,76.4,88.2,100.0,111.8,123.6,138.2,150.0,161.8,176.4,188.2,200.0,211.8,223.6,238.2,250.0,261.8};
//----
//--- bars minimum for calculation
#define BAR_LIMIT  100
#define KEY_UP     38 
#define KEY_DOWN   40 
//---------//

class FiboExtension
  {
//---
    private:
    //--
    int             x_year; // Year 
    int             x_mon;  // Month 
    int             x_day;  // Day of the month 
    int             x_hour; // Hour in a day 
    int             x_min;  // Minutes 
    int             x_sec;  // Seconds
    //---
    

    public:
    //--
                    FiboExtension(void);
                    ~FiboExtension(void);
    
    //--
    double          hldif,
                    GrLvl,
                    maxHi,
                    minLo;
    //--
    int             xdis,
                    ydis;
    int             ArLX,
                    hilo;
    int             csec,
                    psec;
    
    
    //--
    int             year,   // Year 
                    mon,    // Month 
                    day,    // Day 
                    hour,   // Hour 
                    min,    // Minutes 
                    sec,    // Seconds 
                    dow,    // Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) 
                    doy;    // Day number of the year (January 1st is assigned the number value of zero)
    //--
    long            ChId;
    //--
    string          indiname;
    string          fbpanl;
    string          fbtext;
    //--
    color           txtnormal;
    //--
    bool            dispp;
    //--
    int             ReqTime(datetime reqtime,const int reqmode);
    int             ThisTime(const int reqmode);
    //--
    string          timehr(int hr,int mn);
    string          ReqDate(int d,int h,int m);    
    //------------
//---
  }; //-end class FiboExtension
//---------//
    
FiboExtension fex;

//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
FiboExtension::FiboExtension(void):
               hldif(0.0),
               GrLvl(0.0),
               maxHi(0.0),
               minLo(0.0),
               xdis(145),
               ydis(45),
               ArLX(0),
               hilo(0),
               csec(0),
               psec(0),
               x_year(0),
               x_mon(0),
               x_day(0),
               x_hour(0),
               x_min(0),
               x_sec(0),
               year(0),
               mon(1),
               day(2),
               hour(3),
               min(4),
               sec(5),
               dow(6),
               doy(7),
               ChId(ChartID()),
               indiname("FibExt261"),
               fbpanl("Fex"),
               fbtext("Fibo_"),
               txtnormal(clrWhite),
               dispp(false)
  {
  }        
//---------//       
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
FiboExtension::~FiboExtension(void)
  {
  } 
//---------//        
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
    //--
    IndicatorSetString(INDICATOR_SHORTNAME,fex.indiname);
    IndicatorSetInteger(INDICATOR_DIGITS,Digits());
    //--
    fex.psec=-1;
//---
   return(INIT_SUCCEEDED);
  }
//---------//              
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//----
    Comment("");
    //--
    ObjectsDeleteAll(0,fex.fbtext,-1,-1);
    ObjectsDeleteAll(0,fex.fbpanl,-1,-1);
    //--
    Print(getUninitReasonText(reason));
    //--
    if(reason==REASON_REMOVE)
      {
       PrintFormat("An indicator %s deletes from the chart..!!",fex.indiname,__FILE__);
      }
    //--
//----
   return;
  }  
//---------//
//+------------------------------------------------------------------+
//| 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[])
  {
//---
//--- Set Last error value to Zero
   ResetLastError();
//--- check for rates total
   if(rates_total<BAR_LIMIT)
      return(0);
   //--
   if(cshift==Yes)
     {
       if(ChartSetInteger(fex.ChId,CHART_AUTOSCROLL,0,false))
          ChartSetInteger(fex.ChId,CHART_AUTOSCROLL,0,true);
       if(ChartSetInteger(fex.ChId,CHART_SHIFT,0,false))
          ChartSetInteger(fex.ChId,CHART_SHIFT,0,true);
     }
   //--
   fex.hilo=BAR_LIMIT;
   //--
   ArraySetAsSeries(open,true);
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true);
   ArraySetAsSeries(close,true);
   ArraySetAsSeries(time,true);
//----
   int Alvl=ArraySize(Lvl);
   fex.ArLX=ArraySize(LvlExp);
   int Alvt=Alvl-1;
   double Lvl100=Lvl[Alvt];
   int cross=int(Alvl/2);
   int crosm=3;
   int f=0;
   fex.maxHi=0;
   fex.minLo=0;
   datetime Cor1,Cor2,CorC,CorL;
   Cor1=time[0];
   Cor2=time[70];
   CorL=time[71];
   CorC=time[35];
   fex.minLo=low[ArrayMinimum(low,0,fex.hilo)];
   fex.maxHi=high[ArrayMaximum(high,0,fex.hilo)];
   fex.hldif=NormalizeDouble(fex.maxHi-fex.minLo,Digits());
   fex.GrLvl=NormalizeDouble(fex.hldif/Lvl100,Digits());
   //--
//----- Time to create the Fibonacci object
   fex.csec=fex.ThisTime(fex.sec);
   //---
   if(fex.csec!=fex.psec)
     {
       if(!fex.dispp)
         {
           for(f=0; f<fex.ArLX; f++)
             {
               CreateTrendLine(fex.ChId,fex.fbtext+"LineLevels_"+string(f),Cor1,fex.minLo+(fex.GrLvl*LvlExp[f]),Cor2,
                               fex.minLo+(fex.GrLvl*LvlExp[f]),1,STYLE_DASHDOT,trenclr,false,true);
               CreateText(fex.ChId,fex.fbtext+"Labels_"+string(f),CorL,fex.minLo+(fex.GrLvl*LvlExp[f]),
                          DoubleToString(LvlExp[f],1),"Bodoni MT Black",8,labelclr,ANCHOR_RIGHT);
               CreateText(fex.ChId,fex.fbtext+"Limit_"+string(f),Cor2,fex.minLo+(fex.GrLvl*LvlExp[f]),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER);
               CreateArrPrice(fex.ChId,fex.fbtext+"LabelPrice_"+string(f),Cor2,fex.minLo+(fex.GrLvl*LvlExp[f]),1,clrSnow,STYLE_SOLID,ANCHOR_LEFT);
               CreateChannel(fex.ChId,fex.fbtext+"LineCross1",Cor2,Cor1,fex.minLo+(fex.GrLvl*Lvl100),fex.minLo+(fex.GrLvl*Lvl[0]),trncross,STYLE_DOT,false);
               CreateChannel(fex.ChId,fex.fbtext+"LineCross2",Cor2,Cor1,fex.minLo+(fex.GrLvl*Lvl[0]),fex.minLo+(fex.GrLvl*Lvl100),trncross,STYLE_DOT,false);
               CreateText(fex.ChId,fex.fbtext+"LineLimit6",Cor1,fex.minLo+(fex.GrLvl*Lvl[0]),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER);
               CreateText(fex.ChId,fex.fbtext+"LineLimit0",Cor1,fex.minLo+(fex.GrLvl*Lvl[Alvt]),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER); 
               CreateText(fex.ChId,fex.fbtext+"StarCross",CorC,fex.minLo+(fex.GrLvl*Lvl[cross]),CharToString(181),"Wingdings",15,cntcross,ANCHOR_CENTER);
             }
           //--
           for(int x=1; x<fex.ArLX; x++)
             {
               CreateTrendLine(fex.ChId,fex.fbtext+"LineLevels_m"+string(x),Cor1,fex.minLo+(-fex.GrLvl*LvlExp[x]),Cor2,
                               fex.minLo+(-fex.GrLvl*LvlExp[x]),1,STYLE_DASHDOT,trenclr,false,true);
               CreateText(fex.ChId,fex.fbtext+"Labels_m"+string(x),CorL,fex.minLo+(-fex.GrLvl*LvlExp[x]),
                          "-"+DoubleToString(LvlExp[x],1),"Bodoni MT Black",8,labelclr,ANCHOR_RIGHT);
               CreateText(fex.ChId,fex.fbtext+"Limit_m"+string(x),Cor2,fex.minLo+(-fex.GrLvl*LvlExp[x]),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER);
               CreateArrPrice(fex.ChId,fex.fbtext+"LabelPrice_m"+string(x),Cor2,fex.minLo+(-fex.GrLvl*LvlExp[x]),1,clrSnow,STYLE_SOLID,ANCHOR_LEFT);
               CreateChannel(fex.ChId,fex.fbtext+"LineCross1m",Cor2,Cor1,fex.minLo+(-fex.GrLvl*Lvl100),fex.minLo+(-fex.GrLvl*Lvl[0]),trncross,STYLE_DOT,false);
               CreateChannel(fex.ChId,fex.fbtext+"LineCross2m",Cor2,Cor1,fex.minLo+(-fex.GrLvl*Lvl[0]),fex.minLo+(-fex.GrLvl*Lvl100),trncross,STYLE_DOT,false);
               CreateText(fex.ChId,fex.fbtext+"LineLimit0m",Cor1,fex.minLo+(-fex.GrLvl*Lvl100),CharToString(119),"Wingdings",15,endclr,ANCHOR_CENTER); 
               CreateText(fex.ChId,fex.fbtext+"StarCrossm",CorC,fex.minLo+(-fex.GrLvl*LvlExp[crosm]),CharToString(181),"Wingdings",15,cntcross,ANCHOR_CENTER);
             }
           //--
         }
       //--
       fex.psec=fex.csec;
       if(fex.dispp) CreateFiboExPanel();
     }
   //---
   ChartRedraw(fex.ChId);
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

bool CreateTrendLine(long     chartid, 
                     string   line_name,
                     datetime line_time1,
                     double   line_price1,
                     datetime line_time2,
                     double   line_price2,
                     int      line_width,
                     int      line_style,
                     color    line_color,
                     bool     ray_right,
                     bool     line_hidden)
  {  
//---
   ObjectDelete(chartid,line_name);
   //--
   if(ObjectCreate(chartid,line_name,OBJ_TREND,0,line_time1,line_price1,line_time2,line_price2)) // create trend line
     {
       ObjectSetInteger(chartid,line_name,OBJPROP_WIDTH,line_width);
       ObjectSetInteger(chartid,line_name,OBJPROP_STYLE,line_style);
       ObjectSetInteger(chartid,line_name,OBJPROP_COLOR,line_color);
       ObjectSetInteger(chartid,line_name,OBJPROP_RAY,ray_right);
       ObjectSetInteger(chartid,line_name,OBJPROP_HIDDEN,line_hidden);
     } 
   else 
      {Print("Failed to create the object OBJ_TREND ",line_name,", Error code = ", GetLastError()); return(false);}
   //--
   return(true);
//---
  } //-end CreateTrendLine()   
//---------//

bool CreateText(long   chart_id, 
                string text_name,
                datetime txt_time,
                double   txt_price,
                string label_text,
                string font_model,
                int    font_size,
                color  text_color,
                int    anchor)
  { 
//--- 
   ObjectDelete(chart_id,text_name);
   //--
   if(ObjectCreate(chart_id,text_name,OBJ_TEXT,0,txt_time,txt_price))
     { 
       ObjectSetString(chart_id,text_name,OBJPROP_TEXT,label_text);
       ObjectSetString(chart_id,text_name,OBJPROP_FONT,font_model); 
       ObjectSetInteger(chart_id,text_name,OBJPROP_FONTSIZE,font_size);
       ObjectSetInteger(chart_id,text_name,OBJPROP_COLOR,text_color);
       ObjectSetInteger(chart_id,text_name,OBJPROP_ANCHOR,anchor);
     } 
   else 
      {Print("Failed to create the object OBJ_TEXT ",text_name,", Error code = ", GetLastError()); return(false);}
   //--
   return(true);
//---
  } //-end CreateText()
//---------//

bool CreateArrPrice(long   chart_id, 
                    string arr_name,
                    datetime arr_time,
                    double arr_price,
                    int    arr_width,
                    color  arr_color,
                    int    arr_style,
                    int    anchor)
  { 
//--- 
   ObjectDelete(chart_id,arr_name);
   //--
   if(ObjectCreate(chart_id,arr_name,OBJ_ARROW_RIGHT_PRICE,0,arr_time,arr_price))
     { 
       ObjectSetInteger(chart_id,arr_name,OBJPROP_COLOR,arr_color);
       ObjectSetInteger(chart_id,arr_name,OBJPROP_STYLE,arr_style);
       ObjectSetInteger(chart_id,arr_name,OBJPROP_WIDTH,arr_width); 
       ObjectSetInteger(chart_id,arr_name,OBJPROP_ANCHOR,anchor);
     } 
   else 
      {Print("Failed to create the object OBJ_ARROW_RIGHT_PRICE ",arr_name,", Error code = ", GetLastError()); return(false);}
   //--
   return(true);
//---
  } //-end CreateArrPrice()
//---------//

bool CreateChannel(long   chart_id, 
                   string ch_name,
                   datetime ch_time1,
                   datetime ch_time2,
                   double ch_price1,
                   double ch_price2,
                   color  ch_color,
                   int    ch_style,
                   bool   ch_ray)
  { 
//--- 
   ObjectDelete(chart_id,ch_name);
   //--
   if(ObjectCreate(chart_id,ch_name,OBJ_CHANNEL,0,ch_time2,ch_price2,ch_time1,ch_price1))
     { 
       ObjectSetInteger(chart_id,ch_name,OBJPROP_COLOR,ch_color);
       ObjectSetInteger(chart_id,ch_name,OBJPROP_STYLE,ch_style);
       ObjectSetInteger(chart_id,ch_name,OBJPROP_RAY,ch_ray);
     } 
   else 
      {Print("Failed to create the object OBJ_CHANNEL ",ch_name,", Error code = ", GetLastError()); return(false);}
   //--
   return(true);
//---
  } //-end CreateChannel()
//---------//

void CreateLabel(long   chartid, 
                 string lable_name, 
                 string label_text,
                 string font_model,
                 int    font_size,
                 color  label_color,
                 int    chart_corner,
                 int    x_cor, 
                 int    y_cor,
                 bool   price_hidden)
  { 
//--- 
   ObjectDelete(chartid,lable_name);
   //--
   if(ObjectCreate(chartid,lable_name,OBJ_LABEL,0,0,0,0,0)) 
     { 
       ObjectSetString(chartid,lable_name,OBJPROP_TEXT,label_text);
       ObjectSetString(chartid,lable_name,OBJPROP_FONT,font_model); 
       ObjectSetInteger(chartid,lable_name,OBJPROP_FONTSIZE,font_size);
       ObjectSetInteger(chartid,lable_name,OBJPROP_COLOR,label_color);
       ObjectSetInteger(chartid,lable_name,OBJPROP_CORNER,chart_corner);
       ObjectSetInteger(chartid,lable_name,OBJPROP_XDISTANCE,WS(x_cor));
       ObjectSetInteger(chartid,lable_name,OBJPROP_YDISTANCE,y_cor);
       ObjectSetInteger(chartid,lable_name,OBJPROP_HIDDEN,price_hidden);
     } 
   else Print("Failed to create the object OBJ_LABEL ",lable_name,", Error code = ", GetLastError());
   //--
   return;
//---
  } //-end CreateLabel()
//---------//

void CreateFiboExPanel()
  {
//---
    CreateButtonTemplate(fex.ChId,fex.fbpanl+"FiboTemplatep",201,344,STYLE_SOLID,5,
                         BORDER_RAISED,clrNONE,clrGreen,clrWhite,CORNER_RIGHT_UPPER,fex.xdis+60,fex.ydis-3,true);
    CreateLabel(fex.ChId,fex.fbpanl+"Head","Fibonacci Extension Levels","Arial Black",8,fex.txtnormal,CORNER_RIGHT_UPPER,fex.xdis+23,fex.ydis+4,true);
    //--
    double FXp[];
    ArrayResize(FXp,fex.ArLX);
    ArraySetAsSeries(FXp,true);
    ArrayCopy(FXp,LvlExp,0,WHOLE_ARRAY);
    //--
    for(int x=fex.ArLX-1; x>=0; x--)
       CreateLabel(fex.ChId,fex.fbpanl+"p_"+string(x),"Level "+DoubleToString(FXp[x],1)+" : "+DoubleToString(fex.minLo+(fex.GrLvl*FXp[x]),Digits()),
                   "Arial Black",7,fex.txtnormal,CORNER_RIGHT_UPPER,fex.xdis+50,fex.ydis+25+(14*x),true);
    //--
    for(int x=1; x<fex.ArLX; x++)
      {
        //string inlevel=DoubleToString(LvlExp[x],1)== "0.0" ? "Level " : "Level -";
        CreateLabel(fex.ChId,fex.fbpanl+"m_"+string(x),"Level -"+DoubleToString(LvlExp[x],1)+" : "
                    +DoubleToString(fex.minLo+(-fex.GrLvl*LvlExp[x]),Digits()),"Arial Black",7,
                    fex.txtnormal,CORNER_RIGHT_UPPER,fex.xdis-45,fex.ydis+11+(14*x),true);
      }
    //--
    fex.dispp=true;
    //--
    ChartRedraw(fex.ChId);
    //--
    return;
//---
   } //-end CreateFiboExPane()
//---------//

int WS(int width) // Width Scaling factor wide button
  {
//---
    int res=0;
    int reswidth=0;
    //--- Calculating the scaling factor wide button on a screen
    int scale_factor=(TerminalInfoInteger(TERMINAL_SCREEN_DPI));
    //Print("scale_factor=(TerminalInfoInteger(TERMINAL_SCREEN_DPI) = "+string(scale_factor));
    // The basic width in the screen points for standard monitors with DPI=96 
    //--- Use of the scaling factor 
    reswidth=(width * scale_factor) / 96;
    double res1=NormalizeDouble(reswidth*1.25,0);
    res=int(res1);
    //--
    return(res);
//---
  } //-end WS()
//---------//

void CreateButtonTemplate(long chartid,
                          string obj_name,
                          int    x_size,
                          int    y_size,
                          int    style,
                          int    width,
                          int    border,
                          color  bordcolor,
                          color  bgcolor,
                          color  objcolor,
                          int    corner,
                          int    x_dist,
                          int    y_dist,
                          bool   hidden)
  {
//---
    ObjectCreate(chartid,obj_name,OBJ_RECTANGLE_LABEL,0,0,0); // create Rectangle Label
    ObjectSetInteger(chartid,obj_name,OBJPROP_XSIZE,WS(x_size)); 
    ObjectSetInteger(chartid,obj_name,OBJPROP_YSIZE,y_size);
    ObjectSetInteger(chartid,obj_name,OBJPROP_STYLE,style);
    ObjectSetInteger(chartid,obj_name,OBJPROP_WIDTH,width);
    ObjectSetInteger(chartid,obj_name,OBJPROP_BORDER_TYPE,border);
    ObjectSetInteger(chartid,obj_name,OBJPROP_BORDER_COLOR,bordcolor);
    ObjectSetInteger(chartid,obj_name,OBJPROP_BGCOLOR,bgcolor); 
    ObjectSetInteger(chartid,obj_name,OBJPROP_COLOR,objcolor);
    ObjectSetInteger(chartid,obj_name,OBJPROP_CORNER,corner); 
    ObjectSetInteger(chartid,obj_name,OBJPROP_XDISTANCE,WS(x_dist));
    ObjectSetInteger(chartid,obj_name,OBJPROP_YDISTANCE,y_dist);
    ObjectSetInteger(chartid,obj_name,OBJPROP_HIDDEN,hidden);
    ChartRedraw();
    //--
    return;
//---
   } //-end CreateButtonTemplate()
//---------//

//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,            // Event identifier
                  const long &lparam,      // Event parameter of long type
                  const double &dparam,    // Event parameter of double type
                  const string &sparam)    // Event parameter of string type
  {
//---
   ResetLastError();
   //--
   static bool keyPressed=false;
   //---
//--- this is an Event of a keystroke
   if(id==CHARTEVENT_KEYDOWN)
     {
      if(lparam==KEY_UP || lparam==KEY_DOWN)
        {
         if(!keyPressed) keyPressed=true;
         else keyPressed=false;
        }
      //--
      switch(int(lparam)) 
        { 
          case KEY_UP: 
             {
               //--
                CreateFiboExPanel();
               //--- unpress the button 
               break;
             }
          //---fex.
          case KEY_DOWN:
             {
               //--
               int ototal=ObjectsTotal(fex.ChId,-1,-1);
               string name;
               for(int i=ototal; i>=0; i--)
                 {
                   name=ObjectName(fex.ChId,i,-1,-1);
                   if(StringFind(name,fex.fbpanl,0)!=-1) ObjectDelete(fex.ChId,name);
                 }
               fex.dispp=false;
               //--- unpress the button 
               break;
             }
           //--
           ChartRedraw(fex.ChId);  
        } 
     }
   //---
   return;
//---
  }
//---------//

string FiboExtension::timehr(int hr,int mn)
  {
//---
    string scon="";
    string men=mn==0 ? "00" : string(mn);
    int shr=hr==24 ? 0 : hr;
    if(shr<10) scon="0"+string(shr)+":"+men+":"+"00";
    else scon=string(shr)+":"+men+":"+"00";
    //--
    return(scon);
//---
  } //-end timehr()
//---------//

string FiboExtension::ReqDate(int d,int h,int m) 
  { 
//---
   MqlDateTime mdt;
   datetime reqtime=0; 
   TimeToStruct(reqtime,mdt);
   x_year=mdt.year; 
   x_mon=mdt.mon; 
   x_day=d; 
   x_hour=h; 
   x_min=m;
   x_sec=mdt.sec;
   //--
   string mdr=string(x_year)+"."+string(x_mon)+"."+string(x_day)+"  "+timehr(x_hour,x_min);
   return(mdr);
//---
  } //-end ReqDate()
//---------//

int FiboExtension::ReqTime(datetime reqtime,const int reqmode) 
  {
    MqlDateTime tm;
    TimeToStruct(reqtime,tm);
    int valtm=0;
    //--
    switch(reqmode)
      {
        case 0: valtm=tm.year; break;        // Return Year 
        case 1: valtm=tm.mon;  break;        // Return Month 
        case 2: valtm=tm.day;  break;        // Return Day 
        case 3: valtm=tm.hour; break;        // Return Hour 
        case 4: valtm=tm.min;  break;        // Return Minutes 
        case 5: valtm=tm.sec;  break;        // Return Seconds 
        case 6: valtm=tm.day_of_week; break; // Return Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) 
        case 7: valtm=tm.day_of_year; break; // Return Day number of the year (January 1st is assigned the number value of zero) 
      }
    //--
    //Print("valtm = "+string(reqmode)+" "+string(valtm));
    return(valtm);
//---
  } //-end ReqTime()
//---------//

int FiboExtension::ThisTime(const int reqmode) 
  {
//---
    MqlDateTime tm;
    TimeCurrent(tm);
    int valtm=0;
    //--
    switch(reqmode)
      {
        case 0: valtm=tm.year; break;        // Return Year 
        case 1: valtm=tm.mon;  break;        // Return Month 
        case 2: valtm=tm.day;  break;        // Return Day 
        case 3: valtm=tm.hour; break;        // Return Hour 
        case 4: valtm=tm.min;  break;        // Return Minutes 
        case 5: valtm=tm.sec;  break;        // Return Seconds 
        case 6: valtm=tm.day_of_week; break; // Return Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) 
        case 7: valtm=tm.day_of_year; break; // Return Day number of the year (January 1st is assigned the number value of zero) 
      }
    //--
    return(valtm);
//---
  } //-end ThisTime()
//---------//

string getUninitReasonText(int reasonCode) 
  { 
//---
   string text=""; 
   //--- 
   switch(reasonCode) 
     { 
       case REASON_PROGRAM:
            text="The EA has stopped working calling by remove function."; break;
       case REASON_REMOVE: 
            text="Program "+__FILE__+" was removed from chart"; break;
       case REASON_RECOMPILE:
            text="Program recompiled."; break;    
       case REASON_CHARTCHANGE: 
            text="Symbol or timeframe was changed"; break;
       case REASON_CHARTCLOSE: 
            text="Chart was closed"; break; 
       case REASON_PARAMETERS: 
            text="Input-parameter was changed"; break;            
       case REASON_ACCOUNT: 
            text="Account was changed"; break; 
       case REASON_TEMPLATE: 
            text="New template was applied to chart"; break; 
       case REASON_INITFAILED:
            text="The OnInit() handler returned a non-zero value."; break;
       case REASON_CLOSE: 
            text="Terminal closed."; break;
       default: text="Another reason"; break;
     } 
   //--
   return text;
//---
  } //-end getUninitReasonText()
//---------//
//+------------------------------------------------------------------+

***Copyright © 2026 3rjfx ~ For educational purposes only.***

No comments :

Post a Comment

Leave A Comment...

** Our mission is to do good and keep moving forward. **

** We sustain our business and hard work through advertising support, which ensures that all tools and programs remain accessible for free. **

** Please disable Ad block in your browser, whitelisting our site or Turn Off Blocking Everywhere in your ad blocker **

** Your understanding helps us keep this website running and ensures that our programs remain available at no cost. **