Advertisement IC Markets

Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Optimize MetaTrader 4, MetaTrader 5, cTrader, and TradingView for speed. Discuss Level II Market Depth (DOM), custom hotkeys, and volume indicators.
Post Reply
PTScalper
Site Admin
Posts: 3306
Joined: Mon Jul 20, 2026 1:28 pm

Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Post by PTScalper »

Are you tracking your live equity drawdown, or only looking at closed account balance? Many traders get blind-sided by floating losses because standard MetaTrader platform features only report drawdown after positions are closed. To solve this, I prepared a lightweight, real-time Equity Drawdown Calculator snippet for both MT4 and MT5.

Why is monitoring real-time equity drawdown critical? When managing prop firm accounts or personal capital, your maximum trailing drawdown is often calculated against your highest peak equity—not your starting balance. If your equity reaches $10,000 and drops to $9,000 before recovering, you experienced a 10% drawdown regardless of whether you closed the trade at a loss or a profit.

How this calculator works:
The code continuously tracks your highest recorded equity peak during the session. On every tick, it compares your live floating equity against that historical high to compute both exact monetary drawdown and percentage drawdown.

Key benefits include:
• Universal Compatibility: Includes ready-to-use functions natively formatted for both MQL4 and MQL5 environments.
• Zero Lag: Evaluates floating profit and loss on every tick event to capture true intrabar equity troughs.
• Automated Risk Management: Can be embedded into existing Expert Advisors to trigger automated position closure, push notifications, or trading lockouts when your maximum threshold is breached.

Check the implementation code above, drop it into your EA or indicator, and take control of your downside risk. Let me know if you need custom modifications!
//--- Global variables to store peak values
double g_peakEquity = 0.0;

//+------------------------------------------------------------------+
//| Function: CalculateEquityDrawdown |
//| Outputs: current monetary drawdown and percentage drawdown |
//+------------------------------------------------------------------+
void CalculateEquityDrawdown(double &drawdownCash, double &drawdownPercent)
{
double currentEquity = AccountEquity();

// Initialize or update peak equity
if(g_peakEquity == 0.0 || currentEquity > g_peakEquity)
{
g_peakEquity = currentEquity;
}

// Calculate cash and percentage drawdown
drawdownCash = g_peakEquity - currentEquity;

if(g_peakEquity > 0.0)
{
drawdownPercent = (drawdownCash / g_peakEquity) * 100.0;
}
else
{
drawdownPercent = 0.0;
}
}

//+------------------------------------------------------------------+
//| Example usage inside OnTick() |
//+------------------------------------------------------------------+
void OnTick()
{
double ddCash = 0.0;
double ddPercent = 0.0;

CalculateEquityDrawdown(ddCash, ddPercent);

// Print to Journal or display on chart comment
Comment(StringFormat("Peak Equity: %.2f | DD ($): %.2f | DD (%%): %.2f%%",
g_peakEquity, ddCash, ddPercent));

// Example risk management trigger (e.g., 10% max drawdown limit)
if(ddPercent >= 10.0)
{
Print("CRITICAL: Maximum drawdown threshold reached!");
// Add position closing or lockout logic here
}
}
//--- Global variables to store peak values
double g_peakEquity = 0.0;

//+------------------------------------------------------------------+
//| Function: CalculateEquityDrawdown |
//| Outputs: current monetary drawdown and percentage drawdown |
//+------------------------------------------------------------------+
void CalculateEquityDrawdown(double &drawdownCash, double &drawdownPercent)
{
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);

// Initialize or update peak equity
if(g_peakEquity == 0.0 || currentEquity > g_peakEquity)
{
g_peakEquity = currentEquity;
}

// Calculate cash and percentage drawdown
drawdownCash = g_peakEquity - currentEquity;

if(g_peakEquity > 0.0)
{
drawdownPercent = (drawdownCash / g_peakEquity) * 100.0;
}
else
{
drawdownPercent = 0.0;
}
}

//+------------------------------------------------------------------+
//| Example usage inside OnTick() |
//+------------------------------------------------------------------+
void OnTick()
{
double ddCash = 0.0;
double ddPercent = 0.0;

CalculateEquityDrawdown(ddCash, ddPercent);

// Display on chart comment
Comment(StringFormat("Peak Equity: %.2f | DD ($): %.2f | DD (%%): %.2f%%",
g_peakEquity, ddCash, ddPercent));

// Example risk management trigger (e.g., 15% max drawdown limit)
if(ddPercent >= 15.0)
{
Print("CRITICAL: Maximum drawdown threshold breached!");
// Insert custom order execution / closing logic here
}
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Recommended broker for automated trading & scalping IC Markets
FTtrader
Posts: 954
Joined: Mon Aug 03, 2026 2:43 pm

Re: Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Post by FTtrader »

Hi PTscalper,

here i prepared another version for Pine and Ctrader.

Here is the translation of your MQL4/MQL5 code into Pine Script (Version 5).
Since Pine Script handles state and chart execution differently than MQL, here are a few key adjustments made for TradingView:
strategy.equity is used instead of AccountInfoDouble(). This requires the script to be a strategy.
var is used to declare g_peakEquity. In Pine, var ensures the variable retains its value across historical and real-time bars instead of resetting on every new candle.
table is used to replicate MQL's Comment() function for on-chart display.
calc_on_every_tick=true is added to the strategy declaration to simulate OnTick() behavior during live market data.

Code: Select all

//@version=5
strategy("Equity Drawdown Monitor", overlay=true, calc_on_every_tick=true)

// --- Global variables to store peak values ---
// The 'var' keyword ensures the value is kept across bars
var float g_peakEquity = 0.0

// +------------------------------------------------------------------+
// | Logic: CalculateEquityDrawdown                                   |
// +------------------------------------------------------------------+
// Pine Script doesn't support pass-by-reference function parameters 
// like MQL does (&drawdownCash). Instead, we calculate them directly.

float currentEquity = strategy.equity

// Initialize or update peak equity
if g_peakEquity == 0.0 or currentEquity > g_peakEquity
    g_peakEquity := currentEquity

// Calculate cash and percentage drawdown
float ddCash = g_peakEquity - currentEquity
float ddPercent = g_peakEquity > 0.0 ? (ddCash / g_peakEquity) * 100.0 : 0.0

// +------------------------------------------------------------------+
// | Example usage (Executes on every bar/tick)                       |
// +------------------------------------------------------------------+

// Display on chart comment (Using a table in the top right corner)
var table displayTable = table.new(position.top_right, 1, 1, bgcolor = color.new(color.black, 70), border_width = 1, border_color = color.white)

if barstate.islast // Only update the visual table on the most recent tick/bar to save resources
    string displayText = "Peak Equity: " + str.tostring(g_peakEquity, "#.##") + 
                         "\nDD ($): " + str.tostring(ddCash, "#.##") + 
                         "\nDD (%): " + str.tostring(ddPercent, "#.##") + "%"
    table.cell(displayTable, 0, 0, displayText, text_color = color.white, text_halign = text.align_left)

// Example risk management trigger (e.g., 15% max drawdown limit)
if ddPercent >= 15.0
    // Pine Script's version of Print() is log.info(), log.warning(), or log.error()
    log.error("CRITICAL: Maximum drawdown threshold breached!")
    
    // Insert custom order execution / closing logic here
    // Example to close all open positions:
    // strategy.close_all(comment="Max DD Hit")
FTtrader
Posts: 954
Joined: Mon Aug 03, 2026 2:43 pm

Re: Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Post by FTtrader »

Key Differences to Note:

Function Output: MQL uses pointer/reference parameters (&drawdownCash) to return multiple variables from a void function. Pine Script can return tuples from functions [cash, percent] = calc(...), but calculating it directly in the global scope (as done above) is much more standard and efficient in Pine.

Logging vs. Printing: Print() in MQL goes to the Experts tab. In Pine v5, we use log.error(), log.info(), or log.warning(), which outputs to the Pine Logs pane at the bottom of the screen.

Closing Orders: I commented out a standard command (strategy.close_all()). If your equity drops by 15%, uncommenting that line will immediately liquidate all open strategy positions.
FTtrader
Posts: 954
Joined: Mon Aug 03, 2026 2:43 pm

Re: Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Post by FTtrader »

Here is the translation of your code for cTrader. cTrader uses C# for its automated trading (cBots) and custom indicators.

Since C# handles reference parameters and chart text a bit differently than MQL, here are the key adjustments:

Pass by Reference: C# uses the out keyword instead of & to return multiple values from a void function.

Current Equity: In cTrader, you access the account's equity using Account.Equity.

On-Chart Text: cTrader uses Chart.DrawStaticText to display non-moving text on the chart, which perfectly replaces MQL's Comment().

Risk Parameter: I added the 15% limit as a customizable [Parameter] in the cBot menu so you can adjust it without changing the code.

Code: Select all

using cAlgo.API;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class DrawdownMonitor : Robot
    {
        // --- Global variables to store peak values ---
        private double _peakEquity = 0.0;

        [Parameter("Max Drawdown (%)", DefaultValue = 15.0)]
        public double MaxDrawdownPercent { get; set; }

        protected override void OnStart()
        {
            // Initialize peak equity when the bot starts
            _peakEquity = Account.Equity;
        }

        //+------------------------------------------------------------------+
        //| Example usage inside OnTick()                                    |
        //+------------------------------------------------------------------+
        protected override void OnTick()
        {
            // CalculateEquityDrawdown will assign values to these variables via 'out'
            CalculateEquityDrawdown(out double ddCash, out double ddPercent);

            // Display on chart comment (Top Left Corner)
            string displayText = $"Peak Equity: {_peakEquity:F2} | DD ($): {ddCash:F2} | DD (%): {ddPercent:F2}%";
            Chart.DrawStaticText("DD_Comment", displayText, VerticalAlignment.Top, HorizontalAlignment.Left, Color.White);

            // Example risk management trigger (e.g., 15% max drawdown limit)
            if (ddPercent >= MaxDrawdownPercent)
            {
                Print("CRITICAL: Maximum drawdown threshold breached!");
                
                // Insert custom order execution / closing logic here
                // Example: Close all open positions immediately
                foreach (var position in Positions)
                {
                    ClosePosition(position);
                }
                
                // Stop the bot from running further and opening new trades
                Stop(); 
            }
        }

        //+------------------------------------------------------------------+
        //| Function: CalculateEquityDrawdown                                |
        //| Outputs: current monetary drawdown and percentage drawdown       |
        //+------------------------------------------------------------------+
        private void CalculateEquityDrawdown(out double drawdownCash, out double drawdownPercent)
        {
            double currentEquity = Account.Equity;

            // Initialize or update peak equity
            if (_peakEquity == 0.0 || currentEquity > _peakEquity)
            {
                _peakEquity = currentEquity;
            }

            // Calculate cash drawdown
            drawdownCash = _peakEquity - currentEquity;

            // Calculate percentage drawdown
            if (_peakEquity > 0.0)
            {
                drawdownPercent = (drawdownCash / _peakEquity) * 100.0;
            }
            else
            {
                drawdownPercent = 0.0;
            }
        }
    }
}
FTtrader
Posts: 954
Joined: Mon Aug 03, 2026 2:43 pm

Re: Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Post by FTtrader »

Key Differences to Note:

out Modifier: Unlike MQL's & parameter, you explicitly write out when passing the variables into the function in C# (CalculateEquityDrawdown(out double ddCash, out double ddPercent);).

String Formatting: C# uses string interpolation $"{variable:F2}" to format numbers to 2 decimal places, which is cleaner than MQL's StringFormat().

Closing the Bot: I added the Stop() method inside the critical drawdown block. In cTrader, simply closing positions isn't always enough because OnTick() will keep firing and your bot might immediately open new trades. Stop() halts the cBot entirely.
LondonNewsTrader
Posts: 80
Joined: Mon Sep 21, 2026 9:30 am

Re: Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Post by LondonNewsTrader »

FTtrader wrote:Since Pine Script handles state and chart execution differently than MQL, here are a few key adjustments made for TradingView: strategy.equity is used instead of AccountInfoDouble(). ... calc_on_every_tick=true is added to the strategy declaration to simulate OnTick() behavior
Porting DD monitors across platforms is less about syntax and more about what "live equity" actually means on each stack.

For a London session trader the useful number is floating drawdown against the session peak while news risk is open — not a pretty table that updates on bar close. calc_on_every_tick helps on TradingView; on MT you still want the monitor on a chart that receives ticks during your active window, including into US releases if you leave risk on.

I treat the calculator as a seatbelt next to the calendar: soft warn, then hard flatten. Cross-platform ports are worthwhile so the same rule exists wherever you are clicking.

Does your Pine version reset peak at broker midnight, London midnight, or session start? That choice changes the story on multi-session gold days.
LondonScalper
Posts: 770
Joined: Sat Sep 05, 2026 7:54 am

Re: Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Post by LondonScalper »

FTtrader wrote:Hi PTscalper, here i prepared another version for Pine and Ctrader. Here is the translation of your MQL4/MQL5 code into Pine Script (Version 5) .
Cross-porting an equity DD tool to Pine and cTrader is useful for people who flip platforms. The important bit is still the definition of drawdown — day start versus peak — not the language.

I want the same number on the phone and on the chart. If floating DD hits the soft band, new risk stops; hard band flats. Translations that change the metric by accident are worse than no tool.

Appreciate the careful notes on state differences versus MQL.

Which DD definition do you standardise on across the three platforms?

Once the metric matches, I care about alert latency to the phone. A correct DD number that arrives five minutes late is still a late number.
TheRumpledOne
Posts: 5
Joined: Tue Sep 29, 2026 5:10 pm

Re: Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Post by TheRumpledOne »

TRO_003.png
TRO_003.png (19.81 KiB) Viewed 20 times
Thanks for the code.

I installed it in my Trade Display EA.
IT'S NOT WHAT YOU TRADE, IT'S HOW YOU TRADE IT!
PTScalper
Site Admin
Posts: 3306
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free Tool: Real-Time Equity Drawdown Calculator for MT4 & MT5

Post by PTScalper »

You are welcome :-)

Do you like it?

Or do you have any idea how to make it even better?
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Post Reply