Marginal Drawdown Contribution Analyzer in MQL5: Which Configuration Deepens Your Portfolio Drawdown
Introduction
A trader who runs several Expert Advisors on one account, or one Expert Advisor with many configurations, usually knows each component well. Each one has passed its own backtest, and each one has its own drawdown figure. The account, however, trades one portfolio, and the portfolio has a single equity curve with a single maximum drawdown.
The data the trader actually has is the deal history of the account in MetaTrader 5, where every deal carries a magic number. This leads to a practical question: which configuration contributed most to the realized portfolio drawdown, and which one offset it? A standalone drawdown metric cannot answer this because it ignores timing. A pairwise correlation matrix cannot answer it either because it describes pairs of configurations, not the relation of one configuration to the whole portfolio.
I run a book of several dozen configurations on one account, and this question comes up every time a configuration is added or retired. In this article, we build a tool that answers it from the deal history. By the end, you will have a working Marginal Drawdown Contribution Analyzer that:
- Groups realized results by configuration (magic number, or magic number and symbol) and by trade-server calendar day, and builds the combined portfolio curve from them.
- Measures, for every configuration, how much realized drawdown it adds to the portfolio, how much of the deepest drawdown episodes it produced, and which share of the portfolio variance it carries.
- Raises diagnostic flags (DRAG, LOSS-HEDGE, OVERWEIGHT, and OFFSET), tests each flag for stability across the two halves of the sample, and prints a heuristic A+ to F score with a review list.
Everything runs natively inside MetaTrader 5. No external libraries, no Python, no AI.
This article builds on earlier tools in the same area. The Multi-EA Portfolio Scorer reports standalone drawdowns and pairwise correlations. The Drawdown DNA Analyzer decomposes a single equity curve into episodes. The Random Matrix Theory article denoises the correlation matrix of symbol returns. None of them builds the combined portfolio curve and attributes its drawdown to the components, which is the subject of this article.
Why Standalone Drawdown and Pairwise Correlation Are Not Enough
Consider two configurations with the same standalone drawdown. The first one loses money in the same weeks as the rest of the book. The second one loses money in quiet periods and recovers while the others fall. Their standalone figures are identical, but their effect on the portfolio is opposite. The first deepens the portfolio drawdown, and the second makes it shallower.
A pairwise correlation matrix captures part of this effect, but only for pairs and only on average. A configuration can have low correlation with all others yet lose heavily during the episode that sets the portfolio's maximum drawdown. The covariance of a configuration with the portfolio as a whole is different: it does measure a contribution, namely the contribution to the portfolio variance. The tool uses it for that reason, as one of three measures. Variance, however, is not drawdown. It weighs gains and losses symmetrically and ignores the order of the days, so the tool adds two measures that work on the drawdown itself.
The demonstration portfolio used later in this article shows why the three must be read together. One configuration produced 37.6% of the loss in the deepest drawdown, yet only 11.8% of the loss across the three deepest episodes. Another one loses money over the sample, and its effect on the drawdown reverses between the two halves of the sample. Neither fact is visible in a standalone report.
Three Measures of Contribution
The tool works on a matrix of daily realized results: one row per configuration and one column per day. Let x_i be the daily series of configuration i, and let P be the portfolio series, the sum of all x_i on each day. MaxDD(s) is the maximum drawdown, in account currency, of the cumulative curve of a series s that starts at zero. Because the series hold realized results only, every drawdown in this article is a realized drawdown, not an equity drawdown.
Drawdown added (leave-one-out). The first measure compares the portfolio with and without the configuration:
DDadded_i = MaxDD(P) - MaxDD(P - x_i)
This is a counterfactual on the fixed historical P&L matrix. It assumes that the other configurations would have produced exactly the same results without configuration i. On a live account, removing a configuration can change margin, execution, netting, and the behavior of the others. The real effect can therefore differ.
A positive value means that the realized drawdown is deeper with the configuration in the portfolio. A negative value means that the drawdown of the remaining portfolio is deeper. This can reflect a protective property of the configuration, or it can only mean that removing it moves the worst episode to another period. The stability test described below helps to tell the two cases apart. The measure is not additive: the values of several configurations do not sum to the portfolio drawdown.
Share of the deepest drawdown episodes. The second measure splits the portfolio curve into drawdown episodes: from a peak to the next recovery. For an episode with peak day a and trough day b, the portfolio loss over the days a+1 to b equals the depth of the episode. The share of a configuration is its own result over those days, divided by that loss. Worst% uses the deepest episode, and WorstK% uses the K deepest episodes (K = InpEpisodes, 3 by default):
Worst_i = -Sum_{t in W1}(x_i,t) / Depth_1
WorstK_i = -Sum_{e=1..K} Sum_{t in We}(x_i,t) / Sum_{e=1..K}(Depth_e) Both shares sum to 100% across all configurations. A negative share means that the configuration gained money while the portfolio was falling. Worst% describes a single historical episode. It shows what happened in that interval and does not establish a lasting causal role. For this reason, the tool never reports it alone. WorstK% shows whether the same configuration also dominates other episodes.
Euler variance share. The third measure uses the whole sample. The Euler allocation principle attributes the portfolio variance to its components, and the shares again sum to 100%:
Var_i = Cov(x_i, P) / Var(P)
Variance is a complementary proxy, not a drawdown measure. It treats profitable and unprofitable deviations symmetrically, and it assumes that the daily distribution is stable over the sample. The tool uses it only once: alongside the profit share Net_i / Net(P), to show whether a profitable configuration is compensated for the risk it carries. The drawdown-based flags rely on DDadded and on the episode shares.
A small example makes the first measure concrete. In the demonstration portfolio, the realized maximum drawdown is 2,529.03 and the net result is 13,869.51. The ratio of net profit to drawdown is therefore 5.48. Without the configuration XAUUSD M30 B, the drawdown falls to 1,993.42 and the net result falls to 12,268.11. The ratio rises to 6.15, which is 12.2% better. The configuration is profitable. On this historical matrix, however, the portfolio earned more per unit of realized drawdown without it at its current size.
Flags, Stability, and the Composite Score
The measures feed four diagnostic flags. The sign of the configuration's own result is checked first, and its effect on the drawdown second. Every threshold is an input parameter:
- DRAG: The net result is zero or negative, and DDadded is positive. The configuration lost money and the realized drawdown is deeper with it.
- LOSS-HEDGE: The net result is zero or negative, and DDadded is zero or negative. The configuration lost money, but the drawdown of the remaining portfolio is deeper.
- OVERWEIGHT: The net result is positive, and either Var% exceeds Net% by more than InpExcessShare percentage points or removing the configuration improves the net/DD ratio by more than InpImproveMin percent. If the portfolio has no realized drawdown without the configuration, the second condition holds whenever the remaining net result is positive.
- OFFSET: The net result is positive, OVERWEIGHT does not apply, and DDadded is negative. This flag is informational: it never becomes a review item.
The OVERWEIGHT rule compares the two shares by their difference, not by their ratio. A ratio test is unstable when the profit share is small: a change of a few currency units in the net result could switch the flag on and off. With a difference, a configuration needs a material excess of risk over profit to be flagged.
The default values of all these thresholds are starting settings, not calibrated constants. The section "Sensitivity of the Default Thresholds" below explains the logic behind each default and shows how the demonstration changes when the defaults move.
Stability test. A flag is a description of one historical matrix. Before the tool turns a flag into a review item, it recomputes the evidence on the first and on the second half of the days. A DRAG, LOSS-HEDGE, or OFFSET flag is stable only if DDadded has the same sign in both halves as in the full sample. An OVERWEIGHT flag is stable only if Var% exceeds Net% in both halves. An unstable flag is reported as "no conclusion". The test runs only when each half has at least InpMinDays days. This is a minimal robustness check, not a significance test, and a stable flag is still an in-sample result.
Sample size. InpMinDays (60 by default) is a technical floor: below it, the script stops. Between InpMinDays and InpRobustDays (250 by default), the script still prints the table but labels the run PRELIMINARY, including the grade. The default of 250 days, about one trading year, is my own working rule, not a statistically derived horizon. The section "Sensitivity of the Default Thresholds" below includes a small check of how the results change with the length of the sample.
The portfolio score combines four dimensions, each scaled to the interval [0, 1]:
- Drawdown compression: The sum of the standalone drawdowns divided by the portfolio drawdown. A value of 1 means no diversification benefit, and InpCompTarget sets the value that earns a full score.
- Risk spread: The effective number of risk contributors, computed from the positive Euler shares. InpNeffTarget sets the value that earns a full score.
- Drag penalty: A linear penalty on the share of configurations flagged DRAG. It equals 1 without DRAG flags and falls to 0 when that share reaches InpDragTol.
- Net profit to drawdown: The portfolio ratio divided by InpRetDDTarget.
Compression = Sum_i(MaxDD(x_i)) / MaxDD(P) N_eff = 1 / Sum_i(v_i^2), where v_i = max(Var_i, 0) / Sum_j(max(Var_j, 0)) DragPenalty = clamp(1 - (N_DRAG / N) / InpDragTol, 0, 1) Score = 100 * Sum_k(w_k * s_k) / Sum_k(w_k)
The script validates these inputs before it runs. InpCompTarget and InpNeffTarget must be greater than 1, InpDragTol and InpRetDDTarget must be positive, and every weight must be zero or positive with a positive sum. Under these conditions, each s_k lies in [0, 1] and the score lies in [0, 100]. Multiplying all weights by the same positive constant does not change the result.
The score mixes four quantities of different nature, and its value depends on the chosen targets and weights. It has no statistical interpretation. It is a heuristic for comparing versions of the same portfolio under the same settings, and the script states this in its output.
Architecture of the Marginal Drawdown Contribution Analyzer
The tool is a single script, MarginalDD.mq5, organized into five parts:
- Data loaders: LoadDemo, LoadAccount, and LoadCsv turn a source into raw records of the form (day, configuration, realized result) through AddRecord.
- Matrix builder: BuildMatrix builds the calendar and aggregates the raw records into the configuration by day matrix.
- Drawdown engine: MaxDrawdown and DeepestEpisodes measure the drawdown of any daily series and split it into episodes.
- Contribution analysis: Contribution and Analyze compute the measures, the flags, and the stability test for every configuration.
- Report: PrintScore and PrintReview print the score and the review list; OnStart runs the whole sequence.
- Regression test: RunSelfTest checks the drawdown engine and the episode shares on a small hand-built case.
The helper functions that are not shown below (GetSeries, SumOf, Covariance, PrintTable, and the label functions) are short and fully commented in the attached file.
Declarations
The enumerations select the source, the grouping of account deals, and the flag. All thresholds, targets, weights, and grade boundaries are inputs. Three inputs serve reproducibility: InpDemoFrom and InpDemoDays select a window of the demonstration data, and InpSelfTest runs the regression test described after the main script. Each configuration stores its results in an SConfigResult structure.
//+------------------------------------------------------------------+ //| MarginalDD.mq5 | //| Copyright 2026, Cristian David Castillo Arrieta | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2026, Cristian David Castillo Arrieta" #property link "https://www.mql5.com" #property version "1.12" #property description "Measures how much each configuration adds to the realized drawdown." #property script_show_inputs //--- data source for the analysis enum ENUM_MDD_SOURCE { SOURCE_DEMO=0, // Built-in demonstration portfolio SOURCE_ACCOUNT=1, // Trading deals of the current account SOURCE_CSV=2 // CSV file in MQL5\Files }; //--- how account deals are grouped into configurations enum ENUM_MDD_GROUP { GROUP_MAGIC=0, // One configuration per magic number GROUP_MAGIC_SYMBOL=1 // One configuration per magic and symbol }; //--- diagnostic flag assigned to each configuration enum ENUM_MDD_FLAG { FLAG_NEUTRAL=0, // No flag raised FLAG_OFFSET=1, // Profit, DD deeper without it FLAG_OVERWEIGHT=2, // Profit, risk share >> profit share FLAG_LOSS_HEDGE=3, // Loss, DD deeper without it FLAG_DRAG=4 // Loss, DD shallower without it }; //--- input parameters input ENUM_MDD_SOURCE InpSource=SOURCE_DEMO; // Data source input ENUM_MDD_GROUP InpGroupBy=GROUP_MAGIC; // Grouping of account deals input datetime InpFromDate=D'2020.01.01'; // First date of account history input string InpCsvFile="MarginalDD.csv"; // CSV file (Date,Config,Profit), UTF-8 input int InpDemoFrom=0; // Demo: first day kept (0-based, of 520) input int InpDemoDays=0; // Demo: number of days kept (0 = all) input bool InpSelfTest=false; // Run the regression test instead input int InpMinDays=60; // Technical minimum of days in the calendar input int InpRobustDays=250; // Days below which results are PRELIMINARY input int InpEpisodes=3; // Deepest drawdown episodes for Worst3% input double InpExcessShare=10.0; // Var% minus Net% (points) for OVERWEIGHT input double InpImproveMin=5.0; // Net/DD gain (%) without it for OVERWEIGHT input double InpMaxWindowShare=35.0; // Episode share (%) that triggers a check input double InpCompTarget=5.0; // Compression giving a full score (> 1) input double InpNeffTarget=8.0; // Contributors for a full score (> 1) input double InpDragTol=0.25; // DRAG share giving a zero score (> 0) input double InpRetDDTarget=6.0; // Net/DD giving a full score (> 0) input double InpWCompression=1.0; // Weight: drawdown compression (>= 0) input double InpWSpread=1.0; // Weight: risk spread (>= 0) input double InpWDrag=1.0; // Weight: drag penalty (>= 0) input double InpWRetDD=1.0; // Weight: net profit / drawdown (>= 0) input double InpGradeAPlus=90.0; // Minimum score for A+ input double InpGradeA=80.0; // Minimum score for A input double InpGradeB=70.0; // Minimum score for B input double InpGradeC=60.0; // Minimum score for C input double InpGradeD=50.0; // Minimum score for D //--- results for one configuration struct SConfigResult { string name; // Configuration label double net; // Realized net result over the sample double ddAlone; // Standalone realized maximum drawdown double ddWithout; // Portfolio realized max DD without it double netWithout; // Portfolio net result without it double addedDD; // Portfolio DD minus DD without it double windowShare; // Share of the deepest episode's loss double episodeShare; // Share of the K deepest episodes double varShare; // Euler share of portfolio variance double profitShare; // Share of portfolio net profit int flag; // ENUM_MDD_FLAG value int stable; // 1 stable, 0 unstable, -1 not tested }; //--- raw records before they are aggregated into the daily matrix datetime g_recDay[]; // Calendar day of each record string g_recKey[]; // Configuration label of each record double g_recPnl[]; // Realized result of each record //--- aggregated daily matrix string g_names[]; // Configuration labels datetime g_days[]; // Calendar: all weekdays included double g_pnl[]; // Daily P&L, index = config * days + day int g_nCfg=0; // Number of configurations int g_nDays=0; // Number of days in the calendar uint g_rng=0; // Xorshift32 state for the demo SConfigResult g_res[]; // Results, one per configuration
Part 1: Data Loaders
All loaders pass their records through AddRecord. It truncates the time of each record to midnight, so every record of one calendar day falls into one cell of the matrix. Deal times in MetaTrader 5 are trade-server times, so the days are server calendar days.
//+------------------------------------------------------------------+ //| Adds one raw record. The time is truncated to midnight, so all | //| records of one trade-server calendar day fall into one cell. | //+------------------------------------------------------------------+ void AddRecord(const datetime time,const string key,const double pnl) { int n=ArraySize(g_recDay); ArrayResize(g_recDay,n+1,4096); ArrayResize(g_recKey,n+1,4096); ArrayResize(g_recPnl,n+1,4096); g_recDay[n]=(datetime)((long)time/86400*86400); // truncate to midnight g_recKey[n]=key; g_recPnl[n]=pnl; }
ValidateInputs checks the ranges that the formulas depend on, before any data is loaded:
//+------------------------------------------------------------------+ //| Checks the input ranges that the formulas depend on | //+------------------------------------------------------------------+ bool ValidateInputs() { string err=""; if(InpMinDays<2) err="InpMinDays must be at least 2"; if(InpRobustDays<InpMinDays) err="InpRobustDays must not be below InpMinDays"; if(InpDemoFrom<0 || InpDemoDays<0 || InpDemoFrom+InpDemoDays>520 || (InpDemoDays==0 && InpDemoFrom>0)) err="Demo window: InpDemoFrom needs InpDemoDays > 0, and the sum must not exceed 520"; if(InpEpisodes<1) err="InpEpisodes must be at least 1"; if(InpExcessShare<0.0 || InpImproveMin<0.0 || InpMaxWindowShare<=0.0) err="InpExcessShare and InpImproveMin must be >= 0, InpMaxWindowShare > 0"; if(InpCompTarget<=1.0 || InpNeffTarget<=1.0) err="InpCompTarget and InpNeffTarget must be greater than 1"; if(InpDragTol<=0.0 || InpRetDDTarget<=0.0) err="InpDragTol and InpRetDDTarget must be greater than 0"; if(InpWCompression<0.0 || InpWSpread<0.0 || InpWDrag<0.0 || InpWRetDD<0.0) err="Score weights must not be negative"; if(InpWCompression+InpWSpread+InpWDrag+InpWRetDD<=0.0) err="At least one score weight must be positive"; if(!(InpGradeAPlus>=InpGradeA && InpGradeA>=InpGradeB && InpGradeB>=InpGradeC && InpGradeC>=InpGradeD)) err="Grade boundaries must decrease from A+ to D"; if(err!="") Print("Error: ",err); return(err==""); }
The demonstration loader builds a reproducible book of 12 configurations over 520 trading days. It always generates all 520 days, so the random sequence is the same in every run, and keeps only the days selected by InpDemoFrom and InpDemoDays (all days by default). Four shared factors play the role of FX majors, gold, US indices, and the yen and franc pairs. Each configuration loads on one factor, and it trades on a given day only with a fixed probability. The generator is a small xorshift32 routine with a Box-Muller transform (NextUniform and NextGauss in the attached file). It uses a fixed seed, so every run prints the same report.
//+------------------------------------------------------------------+ //| Builds a reproducible demo book of 12 configurations that share | //| four market factors over 520 trading days. All 520 days are | //| always generated, so the random sequence never changes; only the | //| days InpDemoFrom .. InpDemoFrom + InpDemoDays - 1 are kept. | //+------------------------------------------------------------------+ bool LoadDemo() { //--- label, mean daily result, volatility, factor, factor loading, activity string names[12]={"EURUSD H1 A","EURUSD H4 B","GBPUSD H1 A","GBPUSD H4 B", "AUDUSD H1 A","USDJPY H1 A","XAUUSD H1 A","XAUUSD M30 B", "US500 H1 A","US500 H4 B","NAS100 H1 A","USDCHF H4 A"}; double mu[12] ={3.6,2.8,3.2,2.4,-0.8,2.8,6.0,5.6,3.6,2.8,4.0,2.0}; double sigma[12]={60,45,65,40,50,55,150,140,70,55,80,40}; int fac[12] ={0,0,0,0,0,3,1,1,2,2,2,3}; double beta[12] ={0.55,0.55,0.55,0.40,0.30,0.20,0.80,0.80,0.60,-0.45,0.60,0.20}; double act[12] ={0.70,0.55,0.65,0.50,0.60,0.60,0.75,0.80,0.65,0.55,0.70,0.50}; g_rng=20261012; // fixed seed: same report every run int last=(InpDemoDays>0 ? InpDemoFrom+InpDemoDays : 520); datetime day=D'2024.01.01'; for(int d=0; d<520; d++) { //--- skip weekends so the calendar looks like a trading calendar MqlDateTime dt; TimeToStruct(day,dt); while(dt.day_of_week==0 || dt.day_of_week==6) { day+=86400; TimeToStruct(day,dt); } //--- four shared factors: FX majors, gold, US indices, yen and franc double f[4]; for(int k=0; k<4; k++) f[k]=NextGauss(); for(int c=0; c<12; c++) { double e=NextGauss(); double u=NextUniform(); double pnl=0.0; //--- the configuration trades on this day only with probability act[c] if(u<act[c]) pnl=mu[c]/act[c]+sigma[c]*(beta[c]*f[fac[c]]+MathSqrt(1.0-beta[c]*beta[c])*e); //--- every day consumes the same random numbers; only the window is kept if(d>=InpDemoFrom && d<last) AddRecord(day,names[c],pnl); } day+=86400; } if(InpDemoFrom>0 || last<520) PrintFormat("Demo window: days %d to %d of 520 (0-based)",InpDemoFrom,last-1); return(true); }
The account loader reads trading deals only (DEAL_TYPE_BUY and DEAL_TYPE_SELL), which excludes balance, credit, and bonus entries. The value of each deal is profit plus swap plus commission plus fee. An entry deal has no profit, so it contributes its costs, and an exit deal contributes its realized profit. The tool therefore works on realized results, closing profit and all trading costs together, rather than on closed trades alone.
A manually closed position has magic 0 on its closing deal. The loader first selects the whole history, so that positions opened before InpFromDate are visible. It then builds a sorted map from DEAL_POSITION_ID to the magic of the entry deals. A magic-0 deal is then assigned to the opening magic of its position. Two cases cannot be resolved this way. A position whose entry deals carry different magics is marked as mixed. A position without an entry deal with a non-zero magic cannot be matched. These two cases are grouped into separate configurations ("Magic 0 mixed" and "Magic 0 unassigned"). The log reports how many deals fall into each. On a netting account, the loader also reports how many positions were opened by several magics, because the result of such a position cannot be split exactly between them.
//+------------------------------------------------------------------+ //| Binary search of a position in the sorted map [position, magic]. | //| Returns the magic, -1 for a position opened by several magics, | //| or 0 when the position is not in the map. | //+------------------------------------------------------------------+ long FindOpeningMagic(const long &map[][2],const long pos) { int lo=0,hi=ArrayRange(map,0)-1; while(lo<=hi) { int mid=(lo+hi)/2; if(map[mid][0]==pos) return(map[mid][1]); if(map[mid][0]<pos) lo=mid+1; else hi=mid-1; } return(0); }
//+------------------------------------------------------------------+ //| Reads the trading deals of the account and groups them. The | //| result of a deal is profit + swap + commission + fee, so entry | //| deals add their costs and exit deals add their realized profit. | //+------------------------------------------------------------------+ bool LoadAccount() { //--- the whole history is selected, so a position opened before InpFromDate is still found if(!HistorySelect(0,TimeCurrent())) { Print("Error: HistorySelect failed, code ",GetLastError()); return(false); } int total=HistoryDealsTotal(); //--- first pass: [position, magic] of every entry deal with a non-zero magic long raw[][2]; int nRaw=0; for(int i=0; i<total; i++) { ulong ticket=HistoryDealGetTicket(i); if(ticket==0 || HistoryDealGetInteger(ticket,DEAL_ENTRY)!=DEAL_ENTRY_IN) continue; long magicIn=HistoryDealGetInteger(ticket,DEAL_MAGIC); if(magicIn==0) continue; ArrayResize(raw,nRaw+1,1024); raw[nRaw][0]=HistoryDealGetInteger(ticket,DEAL_POSITION_ID); raw[nRaw][1]=magicIn; nRaw++; } ArraySort(raw); // sorts the rows by position //--- one row per position; -1 marks a position opened by different magics long map[][2]; int nMap=0,mixed=0; for(int i=0; i<nRaw; i++) { if(nMap>0 && map[nMap-1][0]==raw[i][0]) { if(map[nMap-1][1]!=raw[i][1] && map[nMap-1][1]!=-1) { map[nMap-1][1]=-1; mixed++; } continue; } ArrayResize(map,nMap+1,1024); map[nMap][0]=raw[i][0]; map[nMap][1]=raw[i][1]; nMap++; } //--- second pass: one record per trading deal inside the selected period int reassigned=0,unassigned=0; for(int i=0; i<total; i++) { ulong ticket=HistoryDealGetTicket(i); if(ticket==0) continue; //--- keep trading deals only: balance, credit and bonus entries are skipped long type=HistoryDealGetInteger(ticket,DEAL_TYPE); if(type!=DEAL_TYPE_BUY && type!=DEAL_TYPE_SELL) continue; datetime time=(datetime)HistoryDealGetInteger(ticket,DEAL_TIME); if(time<InpFromDate) continue; double pnl=HistoryDealGetDouble(ticket,DEAL_PROFIT)+ HistoryDealGetDouble(ticket,DEAL_SWAP)+ HistoryDealGetDouble(ticket,DEAL_COMMISSION)+ HistoryDealGetDouble(ticket,DEAL_FEE); long magic=HistoryDealGetInteger(ticket,DEAL_MAGIC); string key=""; //--- a manual close has magic 0: use the magic of the deal that opened the position if(magic==0) { long found=FindOpeningMagic(map,HistoryDealGetInteger(ticket,DEAL_POSITION_ID)); if(found>0) { magic=found; reassigned++; } else { key=(found==-1 ? "Magic 0 mixed" : "Magic 0 unassigned"); unassigned++; } } if(key=="") key="Magic "+IntegerToString(magic); if(InpGroupBy==GROUP_MAGIC_SYMBOL) key+=" "+HistoryDealGetString(ticket,DEAL_SYMBOL); AddRecord(time,key,pnl); } //--- report every attribution compromise in the log if(reassigned>0) PrintFormat("Note: %d magic-0 deals were assigned to their opening magic",reassigned); if(unassigned>0) PrintFormat("Warning: %d magic-0 deals have no single opening magic; "+ "they form their own configuration",unassigned); if(AccountInfoInteger(ACCOUNT_MARGIN_MODE)==ACCOUNT_MARGIN_MODE_RETAIL_NETTING) PrintFormat("Warning: netting account; %d positions were opened by several magics, "+ "so their results cannot be split exactly",mixed); return(true); }
A magic number is a proxy for a configuration, not a definition of one. A single magic can cover several versions, parameter sets, or symbols, and one configuration can change its magic over time. Grouping by magic number and symbol helps in the first case. For anything finer, the CSV source lets you assign the configuration labels yourself.
The CSV loader opens the file as UTF-8 text, so the Unicode minus sign and non-breaking spaces are read correctly. UTF-16 files are not supported. It removes a byte order mark from the header, and the header decides the separator: a semicolon in the header means a semicolon-separated file, and a comma is the default. SplitCsv splits each line and keeps a separator that sits inside double quotes as part of the field:
//+------------------------------------------------------------------+ //| Splits one CSV line into fields. A separator inside double | //| quotes belongs to the field, and "" inside quotes is one quote. | //+------------------------------------------------------------------+ int SplitCsv(const string line,const ushort sep,string &fields[]) { ArrayResize(fields,0,8); string cur=""; bool inQuotes=false; int len=StringLen(line); for(int i=0; i<len; i++) { ushort ch=StringGetCharacter(line,i); if(ch=='"') { if(inQuotes && i+1<len && StringGetCharacter(line,i+1)=='"') { cur+="\""; i++; } else inQuotes=!inQuotes; continue; } if(ch==sep && !inQuotes) { int k=ArraySize(fields); ArrayResize(fields,k+1,8); fields[k]=cur; cur=""; continue; } cur+=ShortToString(ch); } int k=ArraySize(fields); ArrayResize(fields,k+1,8); fields[k]=cur; return(k+1); }
ParseNumber applies a fixed rule instead of a guess. In a comma-separated file, a comma can only appear inside a quoted field, so it groups thousands and the dot is the decimal point. In a semicolon-separated file, the last of the two marks is the decimal point and the other one groups thousands. After this step, the text must be one plain number: an optional leading minus, at least one digit, and at most one dot. A value such as "1.2.3" or "." is rejected. Spaces, apostrophes, the Unicode minus sign, and accounting brackets for negative values are accepted.
//+------------------------------------------------------------------+ //| Converts a number field into a double. In a comma-separated file | //| a comma can only appear inside quotes, so it groups thousands | //| and the dot is the decimal point. In a semicolon-separated file | //| the last of the two marks is the decimal point and the other one | //| groups thousands. Returns false unless the text is one number. | //+------------------------------------------------------------------+ bool ParseNumber(string text,const bool commaDecimal,double &value) { StringReplace(text," ",""); StringReplace(text,ShortToString(0x00A0),""); // non-breaking space StringReplace(text,"'",""); StringReplace(text,ShortToString(0x2212),"-"); // Unicode minus sign bool negative=false; int len=StringLen(text); if(len>2 && StringGetCharacter(text,0)=='(' && StringGetCharacter(text,len-1)==')') { negative=true; text=StringSubstr(text,1,len-2); } int lastDot=-1,lastComma=-1; for(int i=0; i<StringLen(text); i++) { ushort ch=StringGetCharacter(text,i); if(ch=='.') lastDot=i; if(ch==',') lastComma=i; } if(commaDecimal && lastComma>lastDot) { StringReplace(text,".",""); // dots group thousands StringReplace(text,",","."); } else StringReplace(text,",",""); // commas group thousands //--- an optional leading minus, digits, at most one dot, at least one digit int digits=0,dots=0; len=StringLen(text); for(int i=0; i<len; i++) { ushort ch=StringGetCharacter(text,i); if(ch>='0' && ch<='9') digits++; else if(ch=='.') dots++; else if(!(ch=='-' && i==0)) return(false); } if(digits==0 || dots>1) return(false); value=StringToDouble(text); if(negative) value=-value; return(true); }
//+------------------------------------------------------------------+ //| Reads a UTF-8 CSV whose header is Date,Config,Profit. The | //| separator (comma or semicolon) is taken from the header. | //+------------------------------------------------------------------+ bool LoadCsv() { int h=FileOpen(InpCsvFile,FILE_READ|FILE_TXT|FILE_ANSI,'\t',CP_UTF8); if(h==INVALID_HANDLE) { Print("Error: cannot open ",InpCsvFile," in MQL5\\Files, code ",GetLastError()); return(false); } int line=0; int skipped=0; ushort sep=','; while(!FileIsEnding(h)) { //--- in FILE_TXT mode, FileReadString returns one whole line string s=FileReadString(h); line++; StringTrimLeft(s); StringTrimRight(s); if(line==1) { //--- drop a UTF-8 byte order mark; a semicolon in the header sets the separator StringReplace(s,ShortToString(0xFEFF),""); if(StringFind(s,";")>=0) sep=';'; continue; } if(s=="") continue; // blank line string parts[]; if(SplitCsv(s,sep,parts)!=3) { skipped++; continue; } for(int k=0; k<3; k++) { StringTrimLeft(parts[k]); StringTrimRight(parts[k]); } StringReplace(parts[0],"-","."); // 2024-01-05 is read as 2024.01.05 datetime t=StringToTime(parts[0]); double pnl=0.0; if(t<=0 || parts[1]=="" || !ParseNumber(parts[2],sep==';',pnl)) { skipped++; continue; } AddRecord(t,parts[1],pnl); } FileClose(h); if(skipped>0) PrintFormat("Note: %d malformed CSV rows were skipped",skipped); return(true); }
Part 2: Matrix Builder
The calendar includes all weekdays from the first to the last record, plus weekend days that contain records. A weekday without trades in the whole portfolio is therefore present as a column of zeros. This matters for the variance and covariance terms, and for the effective number of contributors, which would otherwise be computed on active days only. The element for configuration c and day d sits at index c * days + d, and several records of one configuration on one day are summed.
//+------------------------------------------------------------------+ //| Aggregates the raw records into a configuration x day matrix. | //| The calendar holds every weekday from the first to the last | //| record, plus any weekend day with records, so days without | //| trades enter the statistics as zero results. | //+------------------------------------------------------------------+ bool BuildMatrix() { int n=ArraySize(g_recDay); if(n==0) return(false); //--- sorted copy of the record days, used for the range and for weekend days datetime tmp[]; ArrayCopy(tmp,g_recDay); ArraySort(tmp); ArrayResize(g_days,0,1024); int j=0; for(datetime day=tmp[0]; day<=tmp[n-1]; day+=86400) { MqlDateTime dt; TimeToStruct(day,dt); bool weekday=(dt.day_of_week>=1 && dt.day_of_week<=5); while(j<n && tmp[j]<day) j++; bool hasRecord=(j<n && tmp[j]==day); if(weekday || hasRecord) { int k=ArraySize(g_days); ArrayResize(g_days,k+1,1024); g_days[k]=day; } } g_nDays=ArraySize(g_days); //--- list of unique configuration labels, in order of first appearance ArrayResize(g_names,0,64); int idx[]; ArrayResize(idx,n); for(int i=0; i<n; i++) { int found=-1; for(int c=0; c<ArraySize(g_names); c++) if(g_names[c]==g_recKey[i]) { found=c; break; } if(found<0) { found=ArraySize(g_names); ArrayResize(g_names,found+1,64); g_names[found]=g_recKey[i]; } idx[i]=found; } g_nCfg=ArraySize(g_names); //--- several records of one configuration on one day are summed ArrayResize(g_pnl,g_nCfg*g_nDays); ArrayInitialize(g_pnl,0.0); for(int i=0; i<n; i++) { int d=FindDay(g_recDay[i]); g_pnl[idx[i]*g_nDays+d]+=g_recPnl[i]; } return(true); }
Part 3: Drawdown Engine
MaxDrawdown measures the drawdown on the cumulative curve of daily results, starting at zero. It returns the drawdown in account currency together with the index of the peak and the index of the trough. The peak is the latest day on which the curve stood at its running maximum before the decline. If the curve returns exactly to a previous maximum and then falls again, the decline is measured from the day of that return. The earlier occurrence of the same maximum is not used. A peak index of -1 means that the decline started from the initial zero level.
//+------------------------------------------------------------------+ //| Maximum drawdown of a daily P&L series in account currency, | //| measured from the running peak of the cumulative curve (which | //| starts at zero). peak is the latest day on which the curve stood | //| at its running maximum before the decline (-1 at the start), and | //| trough is the lowest day. | //+------------------------------------------------------------------+ double MaxDrawdown(const double &x[],int &peak,int &trough) { double eq=0.0,top=0.0,dd=0.0; int topIdx=-1; peak=-1; trough=-1; for(int i=0; i<ArraySize(x); i++) { eq+=x[i]; //--- >= keeps the latest occurrence of an equal peak as the start of a decline if(eq>=top) { top=eq; topIdx=i; } if(top-eq>dd) { dd=top-eq; peak=topIdx; trough=i; } } return(dd); }
DeepestEpisodes splits the same curve into episodes. An episode starts after a peak and ends when the curve returns to that peak or at the end of the sample. The function records the depth, the peak, and the trough of each episode and returns the K deepest ones, deepest first. Its first episode is the one that MaxDrawdown finds. Both functions use the same peak rule: after an exact recovery, the next episode starts on the day of the recovery. The older rule moved the peak only on a strictly new high. With it, the window of the next episode would also include days of the episode that had already ended. Worst% and WorstK% would then credit those days to the wrong configurations.
//+------------------------------------------------------------------+ //| Splits the curve of x into drawdown episodes (from a peak to the | //| next recovery) and returns the K deepest ones, deepest first. | //+------------------------------------------------------------------+ int DeepestEpisodes(const double &x[],const int k,int &peaks[],int &troughs[],double &depths[]) { double ep[],ed[]; int ePk[],eTr[]; int nEp=0; double eq=0.0,top=0.0,depth=0.0; int topIdx=-1,trIdx=-1; int n=ArraySize(x); for(int i=0; i<=n; i++) { bool closeNow=(i==n); if(i<n) { eq+=x[i]; if(eq>=top) closeNow=true; // recovery or a new high ends an episode else if(top-eq>depth) { depth=top-eq; trIdx=i; } } if(closeNow && depth>0.0) { ArrayResize(ed,nEp+1,64); ArrayResize(ePk,nEp+1,64); ArrayResize(eTr,nEp+1,64); ed[nEp]=depth; ePk[nEp]=topIdx; eTr[nEp]=trIdx; nEp++; depth=0.0; } //--- after an exact recovery, the next episode starts from that day if(i<n && eq>=top) { top=eq; // same peak rule as MaxDrawdown() topIdx=i; } } //--- selection of the K deepest episodes int m=MathMin(k,nEp); ArrayResize(peaks,m); ArrayResize(troughs,m); ArrayResize(depths,m); bool used[]; ArrayResize(used,nEp); ArrayInitialize(used,false); for(int s=0; s<m; s++) { int best=-1; for(int e=0; e<nEp; e++) if(!used[e] && (best<0 || ed[e]>ed[best])) best=e; used[best]=true; peaks[s]=ePk[best]; troughs[s]=eTr[best]; depths[s]=ed[best]; } return(m); }
Part 4: Contribution Analysis
Contribution computes DDadded, the Euler share, and the profit share of one configuration over any range of days. Analyze calls it on the full sample and, for the stability test, on each half:
//+------------------------------------------------------------------+ //| Leave-one-out DD, Euler share and profit share of configuration | //| c over the days [from, to). Returns false when the portfolio has | //| no variance in that range; netP receives the portfolio result. | //+------------------------------------------------------------------+ bool Contribution(const int c,const int from,const int to, double &added,double &varShare,double &profitShare,double &netP) { double p[],x[],rest[]; GetSeries(-1,from,to,p); GetSeries(c,from,to,x); ArrayResize(rest,to-from); for(int d=0; d<to-from; d++) rest[d]=p[d]-x[d]; int pk,tr; added=MaxDrawdown(p,pk,tr)-MaxDrawdown(rest,pk,tr); netP=SumOf(p); profitShare=(netP>0.0 ? SumOf(x)/netP : 0.0); double varP=Covariance(p,p); if(varP<=0.0) return(false); varShare=Covariance(x,p)/varP; return(true); }
//+------------------------------------------------------------------+ //| Computes every measure, flag and stability check | //+------------------------------------------------------------------+ void Analyze(const double ddP,const double netP,const int wFrom,const int wTo, const int &epPk[],const int &epTr[],const double epSum) { ArrayResize(g_res,g_nCfg); double ratioP=(netP>0.0 ? netP/ddP : 0.0); int half=g_nDays/2; bool halves=(half>=InpMinDays); // each half must meet the minimum double x[],rest[],p[]; GetSeries(-1,0,g_nDays,p); for(int c=0; c<g_nCfg; c++) { int pk,tr; GetSeries(c,0,g_nDays,x); g_res[c].name=g_names[c]; g_res[c].net=SumOf(x); g_res[c].ddAlone=MaxDrawdown(x,pk,tr); ArrayResize(rest,g_nDays); for(int d=0; d<g_nDays; d++) rest[d]=p[d]-x[d]; g_res[c].ddWithout=MaxDrawdown(rest,pk,tr); g_res[c].netWithout=netP-g_res[c].net; double dummy=0.0; Contribution(c,0,g_nDays,g_res[c].addedDD,g_res[c].varShare,g_res[c].profitShare,dummy); //--- result inside the deepest episode and inside the K deepest episodes double inWin=0.0,inEp=0.0; for(int d=wFrom; d<=wTo; d++) inWin+=x[d]; for(int e=0; e<ArraySize(epPk); e++) for(int d=epPk[e]+1; d<=epTr[e]; d++) inEp+=x[d]; g_res[c].windowShare=-inWin/ddP; g_res[c].episodeShare=-inEp/epSum; //--- flags: the sign of the result first, then the drawdown effect bool overweight=false; if(netP>0.0) { double excess=100.0*(g_res[c].varShare-g_res[c].profitShare); bool better=false; if(g_res[c].ddWithout<=0.0) better=(g_res[c].netWithout>0.0); // removal leaves no realized drawdown else better=(g_res[c].netWithout/g_res[c].ddWithout>(1.0+InpImproveMin/100.0)*ratioP); overweight=(excess>InpExcessShare || better); } if(g_res[c].net<=0.0) g_res[c].flag=(g_res[c].addedDD>0.0 ? FLAG_DRAG : FLAG_LOSS_HEDGE); else if(overweight) g_res[c].flag=FLAG_OVERWEIGHT; else g_res[c].flag=(g_res[c].addedDD<0.0 ? FLAG_OFFSET : FLAG_NEUTRAL); //--- stability: the flag's evidence must hold in both halves of the sample g_res[c].stable=-1; if(halves && g_res[c].flag!=FLAG_NEUTRAL) { double a1=0,v1=0,s1=0,n1=0,a2=0,v2=0,s2=0,n2=0; bool ok1=Contribution(c,0,half,a1,v1,s1,n1); bool ok2=Contribution(c,half,g_nDays,a2,v2,s2,n2); bool same=false; if(g_res[c].flag==FLAG_OVERWEIGHT) same=(ok1 && ok2 && n1>0.0 && n2>0.0 && v1>s1 && v2>s2); else same=(a1*g_res[c].addedDD>0.0 && a2*g_res[c].addedDD>0.0); g_res[c].stable=(same ? 1 : 0); } } }
Part 5: Report
PrintScore computes the four dimensions and the grade. It runs only when the portfolio result is positive, because the net/DD ratio and the profit shares have no meaning otherwise. In that case, the script switches to diagnostic mode: it prints the drawdown measures and the DRAG, LOSS-HEDGE, and OFFSET flags, and skips Net%, OVERWEIGHT, and the score.
//+------------------------------------------------------------------+ //| Computes and prints the heuristic composite score | //+------------------------------------------------------------------+ void PrintScore(const double sumAlone,const double ddP,const double netP,const bool prelim) { //--- effective number of risk contributors from the positive Euler shares double sumPos=0.0,sumSq=0.0; int nDrag=0; for(int c=0; c<g_nCfg; c++) { sumPos+=MathMax(g_res[c].varShare,0.0); if(g_res[c].flag==FLAG_DRAG) nDrag++; } for(int c=0; c<g_nCfg && sumPos>0.0; c++) { double w=MathMax(g_res[c].varShare,0.0)/sumPos; sumSq+=w*w; } double nEff=(sumSq>0.0 ? 1.0/sumSq : 0.0); double dragShare=(double)nDrag/g_nCfg; //--- four dimensions, each scaled to [0, 1]; the weights are non-negative double sComp =Clamp01((sumAlone/ddP-1.0)/(InpCompTarget-1.0)); double sSprd =Clamp01((nEff-1.0)/(InpNeffTarget-1.0)); double sDrag =Clamp01(1.0-dragShare/InpDragTol); double sRetDD=Clamp01((netP/ddP)/InpRetDDTarget); double wSum =InpWCompression+InpWSpread+InpWDrag+InpWRetDD; double score =100.0*(InpWCompression*sComp+InpWSpread*sSprd+ InpWDrag*sDrag+InpWRetDD*sRetDD)/wSum; Print("--- Composite score (heuristic, no statistical interpretation) ---"); PrintFormat("Drawdown compression %.2fx -> %.2f",sumAlone/ddP,sComp); PrintFormat("Risk spread (effective contributors %.2f of %d) -> %.2f",nEff,g_nCfg,sSprd); PrintFormat("Drag penalty (%d of %d configurations flagged DRAG) -> %.2f", nDrag,g_nCfg,sDrag); PrintFormat("Net profit / realized max drawdown %.2f -> %.2f",netP/ddP,sRetDD); PrintFormat("Score %.1f / 100, grade %s%s",score,Grade(score), (prelim ? " (PRELIMINARY)" : "")); }
PrintReview turns stable DRAG, LOSS-HEDGE, and OVERWEIGHT flags into review items. A stable OFFSET flag is not a review item. Removing such a configuration would deepen the realized drawdown, so the flag calls for no action and appears only in the table. Unstable flags of every kind, OFFSET included, are listed with "no conclusion". If no review item remains, the script says that no stable DRAG, LOSS-HEDGE, or OVERWEIGHT flag was raised. An episode concentration is reported only when a configuration exceeds InpMaxWindowShare in the deepest episode and across the K deepest episodes:
//+------------------------------------------------------------------+ //| Prints the review list in the order of the table. Only stable | //| DRAG, LOSS-HEDGE and OVERWEIGHT flags lead to a review item; a | //| stable OFFSET calls for no action and appears in the table only. | //+------------------------------------------------------------------+ void PrintReview(const int &order[]) { Print("--- Review list (in-sample diagnostics, not trading instructions) ---"); int nRec=0; for(int i=0; i<g_nCfg; i++) { int c=order[i]; SConfigResult r=g_res[c]; if(r.flag!=FLAG_NEUTRAL && r.stable==0) { PrintFormat("- %s: %s does not hold in both halves of the sample; no conclusion", r.name,FlagText(r.flag)); nRec++; continue; } string tag=(r.stable==1 ? "" : " (stability not tested)"); if(r.flag==FLAG_DRAG) PrintFormat("- Review %s (DRAG%s): net %.2f, realized DD without it %.2f", r.name,tag,r.net,r.ddWithout); if(r.flag==FLAG_LOSS_HEDGE) PrintFormat("- Review %s (LOSS-HEDGE%s): net %.2f, but realized DD without it %.2f", r.name,tag,r.net,r.ddWithout); if(r.flag==FLAG_OVERWEIGHT) PrintFormat("- Review the size of %s (OVERWEIGHT%s): "+ "%.1f%% of variance, %.1f%% of net", r.name,tag,100.0*r.varShare,100.0*r.profitShare); if(r.flag!=FLAG_NEUTRAL && r.flag!=FLAG_OFFSET) nRec++; //--- a past concentration is reported only when it holds across several episodes if(100.0*r.windowShare>InpMaxWindowShare && 100.0*r.episodeShare>InpMaxWindowShare) { PrintFormat("- Check %s: %.1f%% of the deepest and %.1f%% of the %d deepest episodes", r.name,100.0*r.windowShare,100.0*r.episodeShare,InpEpisodes); nRec++; } } if(nRec==0) Print("- No stable DRAG, LOSS-HEDGE or OVERWEIGHT flag under the current thresholds"); Print("Note: realized (closed) results only; confirm any change out of sample"); }
The Main Script: Putting It All Together
OnStart validates the inputs, loads the selected source, and checks the sample size. It builds the portfolio curve, computes realized drawdown, identifies the deepest episodes, and runs the analysis. It then prints the table, the score, and the review list.
//+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { Print("=== Marginal Drawdown Contribution Analyzer 1.12 ==="); if(!ValidateInputs()) return; if(InpSelfTest) { RunSelfTest(); return; } //--- load the selected source and build the daily matrix bool ok=false; if(InpSource==SOURCE_DEMO) ok=LoadDemo(); else if(InpSource==SOURCE_ACCOUNT) ok=LoadAccount(); else ok=LoadCsv(); if(!ok || !BuildMatrix()) { Print("Error: no data was loaded"); return; } PrintFormat("Data: %d configurations, %d days (%s to %s)",g_nCfg,g_nDays, TimeToString(g_days[0],TIME_DATE),TimeToString(g_days[g_nDays-1],TIME_DATE)); Print("Granularity: realized result (profit + swap + commission + fee) per "+ "configuration and server calendar day; floating P&L is not included"); if(g_nCfg<2 || g_nDays<InpMinDays) { PrintFormat("Error: at least 2 configurations and %d days are required",InpMinDays); return; } bool prelim=(g_nDays<InpRobustDays); if(prelim) PrintFormat("PRELIMINARY: %d days is below InpRobustDays (%d); "+ "flags are indicative only", g_nDays,InpRobustDays); //--- portfolio curve, its realized drawdown and its deepest episodes double port[]; GetSeries(-1,0,g_nDays,port); double netP=SumOf(port); int pk,tr; double ddP=MaxDrawdown(port,pk,tr); if(ddP<=0.0) { Print("Error: the portfolio has no realized drawdown in this sample"); return; } int epPk[],epTr[]; double epDepth[]; int nEp=DeepestEpisodes(port,InpEpisodes,epPk,epTr,epDepth); double epSum=0.0; for(int e=0; e<nEp; e++) epSum+=epDepth[e]; Analyze(ddP,netP,pk+1,tr,epPk,epTr,epSum); //--- portfolio summary double sumAlone=0.0; for(int c=0; c<g_nCfg; c++) sumAlone+=g_res[c].ddAlone; PrintFormat("Portfolio: net %.2f, realized max drawdown %.2f (%s to %s)",netP,ddP, TimeToString(g_days[pk>=0 ? pk : 0],TIME_DATE), TimeToString(g_days[tr],TIME_DATE)); PrintFormat("Sum of standalone drawdowns %.2f, compression %.2fx; "+ "%d deepest episodes: %.2f", sumAlone,sumAlone/ddP,nEp,epSum); int order[]; PrintTable(netP>0.0,order); //--- the score and the profit-based rules need a positive portfolio result if(netP>0.0) PrintScore(sumAlone,ddP,netP,prelim); else Print("Diagnostic mode: the portfolio result is not positive; "+ "Net%, OVERWEIGHT and the score are not computed"); PrintReview(order); }
Running MarginalDD.mq5 on the built-in demonstration portfolio prints the following report in the Experts tab:
=== Marginal Drawdown Contribution Analyzer 1.12 === Data: 12 configurations, 520 days (2024.01.01 to 2025.12.26) Granularity: realized result (profit + swap + commission + fee) per configuration and server calendar day; floating P&L is not included Portfolio: net 13869.51, realized max drawdown 2529.03 (2025.01.27 to 2025.04.28) Sum of standalone drawdowns 11010.06, compression 4.35x; 3 deepest episodes: 6981.98 --- Contribution by configuration (sorted by drawdown added) --- Config Net DDalone DDadded Worst% Worst3% Var% Net% Flag Stable XAUUSD M30 B 1601.40 1365.46 535.61 46.5 32.5 31.7 11.5 OVERWEIGHT yes XAUUSD H1 A 4778.60 1608.29 456.24 33.1 40.7 34.5 34.5 - - EURUSD H1 A -1541.55 1683.00 307.51 12.2 7.7 5.3 -11.1 DRAG no EURUSD H4 B 1546.04 468.90 91.74 3.6 1.9 2.4 11.1 - - GBPUSD H4 B 757.39 617.05 19.24 0.8 3.8 2.3 5.5 - - USDCHF H4 A 913.27 335.21 18.62 0.7 3.1 0.9 6.6 - - US500 H1 A 361.57 934.27 -54.85 0.3 5.8 3.4 2.6 OFFSET yes NAS100 H1 A 301.04 1205.61 -113.45 37.6 11.8 6.4 2.2 OFFSET yes GBPUSD H1 A 334.91 1132.23 -122.51 -4.8 3.8 5.9 2.4 OFFSET no AUDUSD H1 A -135.54 659.48 -237.68 -6.4 -0.7 2.6 -1.0 LOSS-HEDGE no US500 H4 B 1955.89 615.77 -243.54 -9.6 -2.7 1.9 14.1 OFFSET yes USDJPY H1 A 2996.47 384.79 -351.76 -13.9 -7.7 2.7 21.6 OFFSET yes --- Composite score (heuristic, no statistical interpretation) --- Drawdown compression 4.35x -> 0.84 Risk spread (effective contributors 4.27 of 12) -> 0.47 Drag penalty (1 of 12 configurations flagged DRAG) -> 0.67 Net profit / realized max drawdown 5.48 -> 0.91 Score 72.1 / 100, grade B --- Review list (in-sample diagnostics, not trading instructions) --- - Review the size of XAUUSD M30 B (OVERWEIGHT): 31.7% of variance, 11.5% of net - EURUSD H1 A: DRAG does not hold in both halves of the sample; no conclusion - GBPUSD H1 A: OFFSET does not hold in both halves of the sample; no conclusion - AUDUSD H1 A: LOSS-HEDGE does not hold in both halves of the sample; no conclusion Note: realized (closed) results only; confirm any change out of sample
Fig. 1. The report for the demonstration portfolio in the Experts tab.
Regression test. Setting InpSelfTest to true runs a small hand-built case instead of the analysis. It checks the one situation in which the choice of peak rule matters: a curve that returns exactly to its previous maximum and then declines again. Two configurations, Test A and Test B, trade on six days:
Test A: 10, -4, 0, 0, 0, 3 Test B: 0, 0, 4, -7, 2, 3 Portfolio: 10, -4, 4, -7, 2, 6 Equity: 10, 6, 10, 3, 5, 11
The portfolio reaches 10 on day 0, falls to 6, and returns exactly to 10 on day 2. It then falls to 3 on day 3. The deepest episode therefore runs from the peak on day 2 to the trough on day 3, with a depth of 7. The second episode runs from day 0 to day 1, with a depth of 4. Test A has no result inside the deepest episode, so its Worst% is 0% and Test B carries 100%. Across both episodes, Test A lost 4 of 11 and Test B lost 7 of 11, which gives WorstK% values of 36.4% and 63.6%. With the older peak rule, the deepest episode would have been measured from day 0, and Test A would have received 57.1% of it and 72.7% across both episodes. RunSelfTest makes the same calls as OnStart and compares every value with these hand-worked results:
//+------------------------------------------------------------------+ //| Prints one regression-test comparison and returns its result | //+------------------------------------------------------------------+ bool Check(const string label,const double actual,const double expected) { bool ok=(MathAbs(actual-expected)<1e-9); double shown=(MathAbs(actual)<1e-12 ? 0.0 : actual); // avoid printing -0.0000 PrintFormat("%-30s %9.4f expected %9.4f %s",label,shown,expected,(ok ? "PASS" : "FAIL")); return(ok); }
//+------------------------------------------------------------------+ //| Regression test: the portfolio curve recovers exactly to its | //| previous peak (day 2) and then declines again (day 3). The | //| second episode must start at day 2, not at the first peak. | //+------------------------------------------------------------------+ void RunSelfTest() { Print("--- Regression test: exact recovery to a previous peak ---"); //--- two configurations; the portfolio path is 10, -4, +4, -7, +2, +6 double a[6]={10,-4,0,0,0,3}; double b[6]={0,0,4,-7,2,3}; datetime d[6]={D'2024.01.01',D'2024.01.02',D'2024.01.03', D'2024.01.04',D'2024.01.05',D'2024.01.08'}; for(int i=0; i<6; i++) { AddRecord(d[i],"Test A",a[i]); AddRecord(d[i],"Test B",b[i]); } if(!BuildMatrix()) { Print("Regression test: FAIL (no matrix)"); return; } //--- the same calls as OnStart(), with K = 2 episodes double port[]; GetSeries(-1,0,g_nDays,port); int pk,tr; double dd=MaxDrawdown(port,pk,tr); int epPk[],epTr[]; double epDepth[]; int nEp=DeepestEpisodes(port,2,epPk,epTr,epDepth); if(nEp!=2) { PrintFormat("Regression test: FAIL (%d episodes instead of 2)",nEp); return; } Analyze(dd,SumOf(port),pk+1,tr,epPk,epTr,epDepth[0]+epDepth[1]); //--- expected values, worked out by hand in the article bool ok=Check("Max drawdown",dd,7.0); ok=Check("Peak index",pk,2.0) && ok; ok=Check("Trough index",tr,3.0) && ok; ok=Check("Episode 1 peak index",epPk[0],2.0) && ok; ok=Check("Episode 1 trough index",epTr[0],3.0) && ok; ok=Check("Episode 1 depth",epDepth[0],7.0) && ok; ok=Check("Episode 2 peak index",epPk[1],0.0) && ok; ok=Check("Episode 2 trough index",epTr[1],1.0) && ok; ok=Check("Episode 2 depth",epDepth[1],4.0) && ok; ok=Check("Test A Worst%",100.0*g_res[0].windowShare,0.0) && ok; ok=Check("Test B Worst%",100.0*g_res[1].windowShare,100.0) && ok; ok=Check("Test A Worst2%",100.0*g_res[0].episodeShare,400.0/11.0) && ok; ok=Check("Test B Worst2%",100.0*g_res[1].episodeShare,700.0/11.0) && ok; Print(ok ? "Regression test: PASS" : "Regression test: FAIL"); }
Running MarginalDD.mq5 with InpSelfTest set to true prints the following lines in the Experts tab:
=== Marginal Drawdown Contribution Analyzer 1.12 === --- Regression test: exact recovery to a previous peak --- Max drawdown 7.0000 expected 7.0000 PASS Peak index 2.0000 expected 2.0000 PASS Trough index 3.0000 expected 3.0000 PASS Episode 1 peak index 2.0000 expected 2.0000 PASS Episode 1 trough index 3.0000 expected 3.0000 PASS Episode 1 depth 7.0000 expected 7.0000 PASS Episode 2 peak index 0.0000 expected 0.0000 PASS Episode 2 trough index 1.0000 expected 1.0000 PASS Episode 2 depth 4.0000 expected 4.0000 PASS Test A Worst% 0.0000 expected 0.0000 PASS Test B Worst% 100.0000 expected 100.0000 PASS Test A Worst2% 36.3636 expected 36.3636 PASS Test B Worst2% 63.6364 expected 63.6364 PASS Regression test: PASS
Fig. 2. The regression test for an exact recovery to a previous peak.
The peak rule was corrected in version 1.12. The correction does not change any value published in this article, in the demonstration report or in the sensitivity tables. The reason is that the portfolio curve of the demonstration never returns exactly to a previous maximum. I verified this by running every case reported here with both rules.
Reading the Report
The demonstration portfolio receives a B grade with a score of 72.1. Its compression of 4.35x shows real diversification, and its net/DD ratio of 5.48 is close to the target. The score is held back by a risk spread of only 4.27 effective contributors out of 12 and by one DRAG flag.
The table shows where the risk comes from. The two gold configurations carry 66.2% of the portfolio variance together. XAUUSD H1 A is compensated for it: its variance share and its profit share are both 34.5%, so it raises no flag. XAUUSD M30 B carries 31.7% of the variance for 11.5% of the profit and adds 535.61 to the realized drawdown. Its OVERWEIGHT flag holds in both halves of the sample, so it is the only configuration that reaches the review list as a sizing question.
The stability test removes three flags. EURUSD H1 A lost money over the sample and is flagged DRAG, but its DDadded is -36.07 in 2024 and +307.51 in 2025. AUDUSD H1 A is flagged LOSS-HEDGE, yet its effect on the drawdown also changes sign between the halves. GBPUSD H1 A behaves the same way as an OFFSET. On this sample, none of the three has a consistent effect, and the tool draws no conclusion about them.
NAS100 H1 A shows why a single episode is not enough. It produced 37.6% of the loss in the deepest drawdown, but only 11.8% across the three deepest episodes, and removing it deepens the drawdown in both halves. Its large share of the worst episode is specific to that interval and does not recur in the other deep episodes. The review list therefore does not mention it. Four configurations, including USDJPY H1 A and US500 H4 B, are stable OFFSET flags. In both halves, the realized drawdown of the remaining portfolio is deeper without them. Because a stable OFFSET calls for no action, these four configurations appear in the table but not in the review list.
A practical workflow follows from this:
- Run the script on the account history or on exported backtest results that cover at least InpRobustDays days.
- Look at stable flags first. Treat DRAG and OVERWEIGHT items as questions to investigate, not as instructions.
- Change one configuration at a time, and run the script again after each change. Every change alters the contributions of the others.
- Confirm every change on data that was not used for the decision before applying it to a live portfolio.
Sensitivity of the Default Thresholds
Every default threshold is a starting setting chosen by practical logic, not a value derived from data. The logic behind each default is the following:
- InpExcessShare (10 percentage points): With N configurations, an equal share of risk or profit is 100/N percent, or 8.3% for the 12 configurations of the demonstration. Ten points is a little more than one equal share. A configuration is therefore flagged only when its risk share exceeds its profit share by about the weight of a whole configuration.
- InpImproveMin (5%): This is the smallest gain in net profit per unit of realized drawdown that I treat as worth a review. It is a working value, not a measured one.
- InpMaxWindowShare (35%) and InpEpisodes (3): A share of 35% is about four equal shares for 12 configurations. For a book of another size, a value of three to four times 100/N keeps the same meaning. Three episodes is the smallest number that looks beyond a single episode while keeping only deep episodes.
- InpCompTarget (5), InpNeffTarget (8), InpDragTol (0.25), and InpRetDDTarget (6): These set the points at which each score dimension reaches its maximum. They are scaling anchors for comparing versions of one portfolio, not quality standards.
To see how much the results depend on these choices, I ran the demonstration again with alternative values, changing one threshold or one group of score targets at a time. All other inputs kept their defaults:
| Threshold | Values tested | Effect on the demonstration |
|---|---|---|
| InpExcessShare | 5, 10, 15, 20 | No change. XAUUSD M30 B remains the only OVERWEIGHT flag, and it stays stable. Its risk share exceeds its profit share by 20.2 points. |
| InpImproveMin | 2.5, 5, 10 | No change in any flag or in the review list. |
| InpMaxWindowShare | 25, 30, 35, 40, 45 | At 25 and 30, XAUUSD H1 A and XAUUSD M30 B receive an episode check. From 35 upward, no configuration does. |
| InpEpisodes | 1, 2, 3, 5 | With K = 1, XAUUSD M30 B and NAS100 H1 A receive an episode check. With K of 2 or more, no configuration does. |
| InpCompTarget and InpNeffTarget | 3, 5, 7 and 6, 8, 10 (9 pairs) | The score ranges from 62.6 (C) to 80.8 (A). The default pair gives 72.1 (B). |
| InpDragTol | 0.15, 0.25, 0.5 | The score ranges from 66.6 (C) to 76.3 (B). |
| InpRetDDTarget | 4, 6, 8 | The score ranges from 74.3 (B) to 66.4 (C). |
Two conclusions follow. First, the flags of the demonstration do not depend on InpExcessShare and InpImproveMin over a wide range, so its main finding does not hinge on these two defaults. Second, the episode check and the grade are sensitive. The check depends on where InpMaxWindowShare sits relative to the episode shares of the two gold configurations, which lie between 32.5% and 46.5%. The grade moves by up to two letters with the score targets. Before acting on an episode check, run the script again with at least one stricter and one looser value. Compare grades only between runs with identical settings.
Sample length. I also ran the script on shorter windows of the demonstration data: the first and the last N days. I then compared the flags of each window with the flags of the full 520 days. This agreement is a consistency measure, not a ground truth, because the full sample contains each window.
Each window can be reproduced with two inputs. LoadDemo always generates all 520 days and keeps only the days from InpDemoFrom to InpDemoFrom + InpDemoDays - 1, counted from 0. Simply generating fewer days would reproduce the first N days but not the last N days. The procedure is the following:
- Keep every other input at its default value.
- For the first N days, set InpDemoFrom = 0 and InpDemoDays = N.
- For the last N days, set InpDemoFrom = 520 - N and InpDemoDays = N, for example 390 and 130 for the last 130 days.
- Run the script and note the flag of each configuration and the grade on the score line.
- Run it once more with both inputs at 0 for the full sample, and count the configurations whose flag label is identical in the window and in the full run. A configuration without a flag ("-") counts as one label, and stability is not compared.
The windows give the following results:
| Days in the window | Flags that agree with the full sample (first / last window) | Grade (first / last window) |
|---|---|---|
| 130 | 7/5 of 12 | F, 45.5/F, 25.0 |
| 260 | 6/7 of 12 | B, 73.0/F, 30.7 |
| 390 | 9/11 of 12 | C, 69.1/D, 58.9 |
| 520 | 12 of 12 | B, 72.1 |
With half a year of data, the flags agree with the full sample for only five to seven configurations. With one year, agreement is still six or seven out of 12, and only from about 18 months do most flags settle. Part of the grade difference reflects a real change between periods: the second year of the demonstration earned much less than the first. In this demonstration, one year is therefore a minimum for an indicative reading, not a sufficient size. On real books with fewer trades or rarer, clustered losses, the required length can be larger. A formal answer would need a power analysis or a block bootstrap over days, which this article does not attempt.
Applicability and Limitations
Realized, not equity, drawdown. The tool measures realized results only. Floating P&L of open positions is not part of the deal history. For long-holding strategies, grids, martingales, and averaging systems, the equity drawdown can be much deeper than the realized drawdown reported here, and the contributions can differ as well. Every conclusion in the report refers to the realized drawdown.
Daily aggregation. All results of one configuration on one day are summed, and all deals of one day are treated as simultaneous. Intraday declines are invisible. For intraday Expert Advisors, the realized drawdown can be deeper than reported, and the attribution of short episodes can be distorted.
A fixed historical matrix. DDadded and the flags describe the historical P&L matrix as it was. On a live account, removing a configuration can change margin usage, execution, netting, and the behavior of other components. The counterfactual is a description of the sample, not a forecast of the account without the configuration.
Magic numbers and netting. The grouping is only as good as the mapping from magic numbers to configurations. On netting accounts, positions that several Expert Advisors add to cannot be split exactly, and the loader reports how many such positions exist.
Sample size and robustness. All measures are sample statistics without confidence intervals. The half-sample test catches flags whose evidence reverses within the sample, but it is not a significance test. Below InpRobustDays, the whole report is preliminary, and the sample-length check above shows that one year is a minimum for an indicative reading, not a sufficient size. The demonstration portfolio is synthetic and shows one structure, in which configurations move together through shared factors. It does not show how the tool behaves on books whose losses arrive in rare clusters.
Contribution, not cause. A flag describes a statistical contribution in the sample, not its cause. Overfitting, a change in market conditions, a change in execution, or a data error can all produce the same numbers. The leave-one-out measure also answers a removal question, not a resizing question: halving a configuration does not halve its DDadded. The tool complements walk-forward analysis and Monte Carlo testing rather than replacing them.
Possible Extensions
Several extensions follow naturally from this design. The daily matrix could be built from equity snapshots recorded by each Expert Advisor, which would capture floating losses. The variance share could be replaced by a drawdown-based risk contribution, such as the conditional expected drawdown attribution described by Goldberg and Mahmoud. The half-sample test could be replaced by a block bootstrap over days, which would give each flag a frequency of occurrence instead of a yes/no answer. The score could also be returned from OnTester as a custom optimization criterion for multi-configuration Expert Advisors.
Conclusion
We started from the deal history of an account with many configurations. The question was one that standalone reports cannot answer: which configuration contributed most to the depth of the realized portfolio drawdown. Running MarginalDD.mq5 on that history gives the following results:
- The portfolio net result, the realized maximum drawdown with its dates, the drawdown compression, and the depth of the deepest episodes.
- For each configuration, the realized drawdown it adds, its share of the deepest episode and of the K deepest episodes, its share of the variance, and its share of the net profit.
- A diagnostic flag for each configuration, a stability result for each flag, and a review list built from stable DRAG, LOSS-HEDGE, and OVERWEIGHT flags.
- A heuristic A+ to F score that summarizes the portfolio structure, labeled PRELIMINARY on short samples.
Each output answers a specific question. A stable DRAG flag marks a loss-making configuration with which the realized drawdown was consistently deeper. A stable OVERWEIGHT flag marks a profitable configuration whose risk share consistently exceeded its profit share. A stable OFFSET or LOSS-HEDGE flag marks a configuration with which the realized drawdown was consistently shallower. Read the three measures together, treat the flags as questions rather than instructions, change one configuration at a time, and confirm every change out of sample.
The source code is available in the MQL5 CodeBase: Marginal Drawdown Contribution Analyzer in the MQL5 CodeBase.
The following table describes the files that accompany the article.
| File Name | Description |
|---|---|
| MarginalDD | The main script. It loads daily realized results from the demonstration portfolio, the account history, or a CSV file. It then measures the contribution of every configuration to the realized portfolio drawdown and prints the table, the flags, the score, and the review list in the Experts tab. |
| MQL5.zip | An archive whose root is the MQL5 folder, so it unpacks directly into the terminal data folder with every file in its correct place. The script sits in the MQL5\Scripts\MarginalDD folder, ready to compile without moving anything. |
- MetaQuotes, MQL5 Reference: Trade Functions, MQL5 Documentation;
- MetaQuotes, MQL5 Reference: Deal Properties, MQL5 Documentation;
- MetaQuotes, MQL5 Reference: File Functions, MQL5 Documentation;
- D. Tasche, Capital Allocation to Business Units and Sub-Portfolios: the Euler Principle, arXiv:0708.2542, 2008 (origin of the Euler risk contribution).
- L. R. Goldberg and O. Mahmoud, Drawdown: From Practice to Theory and Back Again, Mathematics and Financial Economics, 2016 (drawdown risk attribution).
- Marginal Drawdown Contribution Analyzer source code, MQL5 CodeBase: Marginal Drawdown Contribution Analyzer in the MQL5 CodeBase
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.