Русский
preview
Machine Learning Under Constraint (Part 3): De-Risking Near the Profit Target and the News-Window Rule

Machine Learning Under Constraint (Part 3): De-Risking Near the Profit Target and the News-Window Rule

MetaTrader 5 — Machine learning |
828 1
Patrick Murimi Njoroge
Patrick Murimi Njoroge

Table of Contents

  1. Introduction
  2. Derisking Near the Profit Target
  3. Interaction with the Remaining-Risk Budget
  4. Funded-Stage News Constraint
  5. Making the Calendar Symbol-Aware
  6. Implementation Notes
  7. Conclusion
  8. Attached Files


Introduction

Part 1 generalized the prop-firm rules a sizer enforces into an explicit PropFirmRuleSet, and gave PropFirmAccountState a current_balance that accumulates correctly across an entire challenge — every trading day's realized P&L and fees, banked forward through every reset_daily() call. Part 2 built the modifier that reads the downside half of that state: WParamCalibrator takes risk_budget_pct, the fraction of the loss budget still remaining, and flattens the sizing sigmoid as it is consumed.

This article completes PropFirmAwareSizer.size()'s modifier chain with two further modifiers. derisking_factor reads phase_progress (how much of the profit target has already been reached) and reduces position size as that target approaches, protecting accumulated progress rather than remaining capital. risk_budget_pct and phase_progress are distinct quantities, though not statistically independent: both are computed from the same balance and P&L path, and they can move together or apart. An account can be flush with loss budget while also close to finishing its challenge. news_window_factor reads neither state. It reads the clock and a calendar of event times, under a rule specific to the funded stage of a challenge rather than the evaluation stage. It is a sizing heuristic layered on that rule, not an implementation of the rule's profit accounting, and the calendar's own accuracy matters more than the function's small size would suggest.


Derisking Near the Profit Target

Why Protect the Ceiling

A phase profit target under FundedNext's Stellar 2-Step rules is 8% for the first challenge phase — accumulated gradually, typically across weeks, not won in a single session. Reaching it converts a fixed evaluation fee into a funded account with an open-ended profit share, the convex payoff Part 1 opened with. That framing motivates a sizing rule once progress nears the target: an unconstrained Kelly fraction has no mechanism to recognize that the account is holding something valuable and close to cashing in, and sizes the next trade identically whether the account is at 10% of its target or 95%. Protecting a near-complete pass is a different problem from protecting remaining capital, which is why it needs a second modifier reading a second signal, one derived from the same account history but measuring something different, rather than a more elaborate version of the first.

The option analogy is a motivation, not an argument. An account near its phase target resembles a deep in-the-money option, and one intuition is that the marginal upside from another trade is small next to the downside of a reversal that pushes the account back through the target. The analogy does not determine the sizing curve. The right behavior for an option depends on time to expiry, volatility, the holder's utility, and the exercise rules, and none of those implies a linear reduction between 80% and 100% of the target. derisking_factor is a piecewise-linear heuristic chosen for simplicity; it prices none of the option's mechanics.

derisking_factor

The function is a piecewise-linear heuristic: flat at full size until 80% of the phase target, then declining to a floor at 100%. The floor depends on whether the account has already satisfied the rule set's minimum trading-days requirement. The curve's effect on pass rate and expected value is untested in this article.

def derisking_factor(
    phase_progress: float,
    meets_min_trading_days: bool,
    floor_days_met: float = 0.10,
    floor_days_unmet: float = 0.30,
) -> float:
    if phase_progress < 0.80:
        return 1.0
    floor = floor_days_met if meets_min_trading_days else floor_days_unmet
    slope = (floor - 1.0) / (1.0 - 0.80)
    return float(np.clip(1.0 + slope * (phase_progress - 0.80), floor, 1.0))

Phase Progress

Floor 0.30 (days not yet met)

Floor 0.10 (days already met)

0% – 80% (threshold) 1.000 1.000
85% 0.825 0.775
90% 0.650 0.550
95% 0.475 0.325
100% (target reached) 0.300 0.100

Table 1. derisking_factor at representative phase-progress points, both floors

As established in Part 1's Opinion, the 80% threshold and both floors are a strategy choice about how aggressively to protect an in-hand pass, independent of which firm's rules are in force. meets_min_trading_days is different: it is a fact about the account's progress against a firm rule, not a tunable strategy choice, discussed below. The function otherwise takes no rule set, no account reference, and no phase — the same design pattern Part 1 used for news_window_factor, a pure function that is trivially unit-testable with primitive inputs.

Choosing a threshold and the two floors. 80%, 0.30, and 0.10 are starting values, not tested or universal ones. As a working hypothesis, a high-win-rate, low-variance strategy has little reason to protect progress early, since most of its trades near the target are themselves low-variance, so a later threshold and shallower floors cost little. A strategy that relies on occasional large wins — a lower win rate, fatter tails — has more to lose from one badly timed reversal wiping out weeks of progress, and benefits from de-risking earlier and further. The threshold and floors are not a minor stylistic knob; they are a strategy parameter like any other.

Why meets_min_trading_days Is an Input, Not a Tunable Default

derisking_factor takes meets_min_trading_days as a required argument rather than folding it in as a third tunable default next to the 80% threshold and the two floors. The distinction is not cosmetic. The threshold and floors are a strategy choice, as above. meets_min_trading_days is a fact about the account's current standing against PropFirmRuleSet.min_trading_days, sourced from the property Part 1 added to PropFirmAccountState, and the two-floor policy chosen here cannot be evaluated without it. A single-floor policy would not need the flag; the argument is required by this design, not by the rule set.

The two floors reflect one design decision. While the minimum trading-days requirement is still open, the strategy keeps a higher floor (0.30) so that it can keep accumulating trading days. Once the requirement is met, the floor drops to 0.10. The 0.30 value is not derived from any firm rule. Firms define a qualifying trading day in different ways, and if a day qualifies with any executed trade, no particular size is required. In that case 0.30 carries more risk than the rule demands. Check how your firm defines a trading day, and set floor_days_unmet to the smallest size that qualifies.

0.10 is a starting point, not a derived optimum, and it has no rule-based justification. Once the target is reached and the trading-days requirement is met, the pass condition is satisfied, and further exposure adds risk without advancing it (subject to how the firm evaluates and closes the phase). A floor of 0.0, which stops trading at that point, is the policy most consistent with that objective. The 0.10 default keeps a small exposure alive and is a placeholder; pass floor_days_met=0.0 to go flat.

Whether 80%/0.30/0.10 improves pass rate or expected value versus constant sizing is an empirical question this article does not answer; it trades a certain cost (forgone size late in a challenge) against an uncertain benefit (protection against a reversal that would have failed the challenge anyway), and resolving it needs backtesting across many simulated attempts rather than reasoning about the curve's shape alone.


Interaction with the Remaining-Risk Budget

What Happens When Both Modifiers Are Active

WParamCalibrator responds to risk_budget_pct: how much room remains before failure. derisking_factor responds to phase_progress: how close the account is to success. A good day, late in a challenge, is exactly the scenario where these pull in different directions rather than agreeing:

The derisking_factor curve and its interaction with the budget-driven ceiling

The derisking_factor curve, and a simulated profitable day where the budget-driven ceiling and the derisking ceiling diverge

Figure 1. Two-panel illustration of the derisking curve and its interaction with the budget-driven ceiling

  • Left panel: derisking_factor against phase_progress for both floors — flat below 80%, then separating to 0.30 or 0.10 depending on meets_min_trading_days.
  • Right panel: a simulated account starting at 87.5% phase progress, having a good day with no material losses. cal_bet_size — the budget-only ceiling from Part 2 — stays near its 0.98 cap throughout, since the daily limit keeps expanding with the day's profit. The combined ceiling, cal_bet_size × derisking_factor, falls from about 0.72 to 0.47 as phase_progress climbs to 94.8%.

The right panel answers the question Part 2's conclusion deferred: WParamCalibrator alone would size this account up, because the budget genuinely supports it. derisking_factor pulls the other way, and both act on the final size, because PropFirmAwareSizer.size() multiplies every modifier together rather than taking a minimum: combined_modifier = sigmoid_scale × derisking × news (news, covered in Section 4, follows the identical rule but depends on neither budget nor phase progress). Multiplication is not min(). Every active modifier below 1.0 keeps reducing the result, so two moderate restrictions combine into a tighter one than either alone: modifiers of 0.8 and 0.7 give 0.56, not 0.7. No modifier needs to know the others exist, which keeps each one independently testable, at the cost of compounding restrictions rather than applying only the strictest.

Multiplication has a second consequence: the same combined ceiling can arise from two different account situations, and final_size alone does not say which. A budget at 1.4% remaining with 90% phase progress, and a budget at 0.91% remaining with 20% phase progress, both combine to exactly 0.637: one account close to finishing and safe on capital, the other early and running low on capital, arriving at the identical position size. The diagnostic columns returned by PropFirmAwareSizer.size() — cal_bet_size, derisking, w_param — are required to tell the two cases apart.

This demonstrates one deliberately favorable day. When both signals tighten at once, for example after a large intraday loss that leaves the account close to its target, the reductions compound. Test the combined ceiling against your own configuration before trusting it near both boundaries at once.

Production Note: One State Snapshot Per Event

PropFirmAwareSizer.size() computes derisking once per call, from a single PropFirmAccountState snapshot, and applies it uniformly across every event in whatever batch is passed to that call. This is correct for a live strategy calling .size() once per bar with a freshly updated state. It is incorrect the moment .size() is called once across a batch of events spanning more than one meaningfully different phase_progress — precisely what a vectorized backtest tends to do.

# Wrong: one snapshot, never advanced, sizes the whole window from the initial state
state = PropFirmAccountState(initial_balance=100_000.0, phase=phase, rule_set=rules)
sizing = sizer.size(events=all_events, prob=all_probs, pred=all_preds, state=state)

# Correct: before each event, apply only P&L from trades that closed before its entry
state = PropFirmAccountState(initial_balance=100_000.0, phase=phase, rule_set=rules)
closed = realized_pnl.sort_index() # indexed by trade close time
costs = fees.reindex(closed.index, fill_value=0.0)
cursor, rows = 0, []
for ts in all_events.index:
    n = closed.index.searchsorted(ts, side="left")
    if n > cursor:
        state.update(realized_pnl_delta=closed.iloc[cursor:n].sum(),
                     unrealized_pnl=0.0,
                     fees_and_swaps=costs.iloc[cursor:n].sum())
        cursor = n
    rows.append(sizer.size(events=all_events.loc[[ts]], prob=all_probs.loc[[ts]],
                           pred=all_preds.loc[[ts]], state=state, current_time=ts))
sizing = pd.concat(rows)

The corrected version replaces one vectorized call with a Python-level loop over events. Its cost is usually small next to model training and label computation, but it is not negligible in general. For a large event-level backtest the loop can become the bottleneck, so profile it before assuming otherwise. It is also the only version where state.phase_progress at each call reflects the account as it stood at that point in history.

Two details of the loop matter. It applies only P&L from trades that closed strictly before the event's entry time, because updating the state with an event's own outcome before sizing it is look-ahead bias: the size would be computed after the result is known. It also indexes P&L by trade close time, so overlapping positions do not leak their eventual outcomes into events that opened while they were still running. The sketch passes unrealized_pnl=0.0 and omits the daily reset for brevity. A production loop marks open positions to market and calls state.reset_daily() at each day boundary, which is also what advances the trading-days count behind meets_min_trading_days.

The dangerous direction is a stale snapshot, typically the initial one, applied uniformly: every late-window event, where phase_progress was genuinely near 100% and should have been suppressed toward the floor, gets sized as if derisking_factor were still 1.0. That means the account takes its largest, least-restricted positions exactly when closest to a completed pass, which is what derisking_factor exists to prevent. It also produces no error, warning, or obviously wrong number. Only a comparison against the correct per-event calculation reveals it.

The opposite mistake, applying an end-of-window snapshot uniformly, fails differently. phase_progress is near its maximum for the whole window, so every early event is suppressed using information that was not available when it was sized. That is look-ahead bias, and it understates early-window sizes.


Funded-Stage News Constraint

What FundedNext Actually Restricts

FundedNext restricts nothing during the Challenge Phases, on any Stellar model. Once an account transitions to the FundedNext Account, a News Reward Share Rule applies: trades opened or closed within five minutes before or after a listed high-impact news event have only 40% of their profit counted toward the account balance, for a symmetric ten-minute window. Losses inside that window count in full; only profit is haircut. In accounting terms, a trade opened or closed inside the window credits 0.4 × P&L when P&L is positive and the full P&L when it is negative. Existing positions can be held through a news event without restriction, since the rule triggers on execution, not on merely being in a trade while news prints. The rule also applies only to news that directly correlates with the traded pair — FundedNext's own example: a EUR/USD trade during high-impact USD or EUR news is subject to the haircut; the same trade during high-impact CNY news is not.

news_window_factor

The function is a short, phase-gated window check that converts every timestamp to UTC first (see Timestamp Normalization):

def news_window_factor(
    current_time: datetime,
    news_times: list[datetime],
    news_profit_credit: float,
    window_minutes: float = 5.0,
    phase: Phase = Phase.CHALLENGE_PHASE_1,
) -> float:
    if phase != Phase.FUNDED or not news_times or news_profit_credit >= 1.0:
        return 1.0
    window = pd.Timedelta(minutes=window_minutes)
    ct = _to_naive_utc(current_time)
    for nt in news_times:
        if abs(ct - _to_naive_utc(nt)) <= window:
            return news_profit_credit
    return 1.0

The phase gate follows the rule's scope: challenge-phase calls exit immediately at 1.0, since FundedNext documents no news restriction there. window_minutes defaults to 5.0 and is used as a half-width, reproducing the documented ten-minute total window without a separate before/after pair. news_profit_credit comes from PropFirmRuleSet, per Part 1's argument for keeping firm-level facts on the rule set rather than hardcoded here.

The rule is an accounting rule, and news_window_factor does not implement it. The function returns a size multiplier for an entry evaluated at current_time, which is a trading policy layered on the rule. The two differ in three ways:

  • Payoff shape: scaling a position by 0.40 scales profit and loss alike. A full-size trade inside the window would credit 0.40 of its profit and all of its loss. The scaled trade credits 0.16 of the full-size profit and 0.40 of the full-size loss. The multiplier trades reward for lower loss exposure, so it is a conservative heuristic, not an exact model.
  • Closing events: the rule also triggers on closes, and the function sees only current_time. A position opened outside a window that closes or is stopped out inside a later one is not covered.
  • Execution type: the function cannot tell an entry from an exit, or from an existing position being held through the news. Call it for entry sizing only. Exits inside a window need separate handling by the calling code.

The news-window step function and the symbol-correlation gap

The news-window step function and the symbol-correlation gap

Figure 2. Two-panel illustration of news_window_factor's behavior

  • (a): news_window_factor across a 40-minute window. The challenge-phase line stays flat at 1.0; the funded-phase line drops to 0.40 for exactly the documented ten minutes and returns to 1.0 immediately outside it.
  • (b): a EUR/USD trade at the exact moment of a JPY-only event. An unfiltered calendar haircuts it to 0.40 by mistake; a symbol-filtered calendar (Section 5) correctly leaves it at 1.00.

How Often Does This Actually Matter?

A step function confirms the mechanism works; it says nothing about how often a real trading day intersects a news window. The answer hinges on one question: does the strategy's entry timing have anything to do with when news gets released?

An illustrative year of USD high-impact events (NFP, CPI, and the eight FOMC decisions, 32 events total) gives something to test two trading patterns against. Both trade sets are synthetic.

How often trade timing collides with a news window

How often trade timing collides with a news window

Figure 3. Two-panel illustration of the news-window collision rate by strategy type

  • (a): 780 trades/year with entry timing unrelated to the news calendar land in a news window zero times over the simulated year. 616 trades/year from a news-reactive breakout strategy land in a news window 3.25% of the time.
  • (b): splitting the reactive strategy's trades by origin shows where that comes from. The 96 trades placed deliberately after a release collide 19.8% of the time; the other 520, unrelated to any specific event, collide at 0.19% — indistinguishable from panel (a).

In this illustration, the collision rate depends on the strategy's timing, not on the rule. A strategy whose entries are unrelated to the calendar, such as a carry strategy or a session-open breakout, collided with a news window zero times in the simulated year. That is one draw from a rare-event process. It shows the rule can go unmet for a year; it does not show the effect is immaterial, and only collisions were simulated, not the cost of the haircut. Repeat the simulation across many seeds, and use your own trade timestamps and news calendar, before concluding that modeling the rule can be skipped. A strategy built around trading the volatility that follows a release met this rule on purpose, in roughly one of every five deliberate entries. For that strategy, the news rule directly taxes the trades the strategy exists to take.


Making the Calendar Symbol-Aware

Why Naive Calendars Are Wrong

news_times is typed as list[datetime], a flat list of moments, with no instrument, currency, or event identity attached. news_window_factor checks only whether current_time falls within the window of any entry; it has no way to ask whether an entry has anything to do with the symbol being sized, because that information was never in the calendar to begin with. Feeding it an unfiltered global calendar — the natural shape of most third-party economic calendar feeds — produces the wrong answer whenever a currency-irrelevant event falls inside a position's window, inflating the collision rate (Section 4) with false positives on every symbol traded.

Filtering by TransactionCostModel Currencies

The fix does not belong inside news_window_factor itself; teaching it about currency correlation would bolt a second responsibility onto a function whose entire value is being trivially easy to reason about. The fix belongs upstream, and it turns out to almost already exist. Part 14'sTransactionCostCollector.mq5 reads SYMBOL_CURRENCY_BASE and SYMBOL_CURRENCY_PROFIT from the broker's own symbol specification and writes both to its export CSV. TransactionCostModel never read them — load_cost_model() stopped at symbol, digits, point, pip_factor, tick_size, tick_value, and contract_size. The currency fields were collected, written to disk, and silently discarded on the Python side.

# TransactionCostModel -- three fields alongside the other symbol properties
@dataclass
class TransactionCostModel:
    symbol:          str
    spread_pips:     float
    ...
    currency_base:   str = ""
    currency_profit: str = ""
    currency_margin: str = ""
    ...

    @property
    def correlated_currencies(self) -> set[str]:
        """Currencies whose high-impact news is relevant to this symbol,
        per FundedNext's own correlation rule. Margin currency is about
        account funding, not price sensitivity, so it is recorded but
        not included here."""
        return {c for c in (self.currency_base, self.currency_profit) if c}
# load_cost_model() -- read what the CSV already has, next to the other
# symbol_properties reads
currency_base   = get("symbol_properties", "currency_base")
currency_profit = get("symbol_properties", "currency_profit")
currency_margin = get("symbol_properties", "currency_margin")
...
return TransactionCostModel(
    ...,
    currency_base=currency_base,
    currency_profit=currency_profit,
    currency_margin=currency_margin,
)

With that in place, the calendar filter reads correlation off the cost model instead of a second, independently maintained table:

def filter_news_by_cost_model(
    calendar: list[tuple[datetime, str]],
    cost_model: TransactionCostModel,
) -> list[datetime]:
    """calendar: (event_time, currency) pairs. Returns only times whose
    currency is one of cost_model's correlated currencies."""
    relevant = cost_model.correlated_currencies
    if not relevant:
        raise ValueError(
            f"{cost_model.symbol!r} has no currency_base/currency_profit set -- "
            f"re-run TransactionCostCollector.mq5 or check the loaded CSV."
        )
    return [t for t, ccy in calendar if ccy in relevant]

Run against Figure 2(b)'s scenario — a EUR/USD cost model, correlated_currencies = {"EUR", "USD"}, a calendar with both the EUR event and the JPY-only one — filter_news_by_cost_model keeps the EUR event and drops the JPY one, reproducing the 1.00 FundedNext's rule says should apply. This is broker-verified rather than hand-typed, covers every FX symbol a cost model has already been collected for, and avoids a second source of truth for a fact TransactionCostModel already holds. The fix required no change on the MQL5 side: the collector has exported these fields since its first version; the gap was three missing reads on the Python side.

Scope. Base and profit currency are a sound relevance key for FX pairs and a weaker one elsewhere. An index CFD, a metal, an energy contract, or a crypto CFD responds to news that its quote currency does not capture: for XAUUSD, XAU is not a calendar currency, and USD is only a partial proxy. Events tied to a common currency or to global releases may also not map to a single ISO code. Whether the firm treats such news as correlated with a symbol is the firm's determination. For non-FX symbols, replace correlated_currencies with an explicit per-symbol mapping rather than relying on the specification fields.

A Companion Collector for the Calendar

filter_news_by_cost_model needs a calendar, and the official MetaTrader5 Python package has no binding for MQL5's Economic Calendar functions at all — a gap confirmed on MQL5's own forum. MQL5's documentation also states that calendar functions cannot be called inside the Strategy Tester, returning FUNCTION_NOT_ALLOWED on every attempt. The fix follows the same pattern this series already uses for transaction costs: export from an MQL5 script, load the CSV in Python. CalendarCollector.mq5, attached below, follows the same shape as TransactionCostCollector.mq5 and the same five-column CSV format, resolving each calendar value to its event and country for the ISO currency code the filter above uses, keeping only events at or above a configurable importance threshold:

input int    InpLookbackDays  = 90;   // Days of history to export (for backtesting)
input int    InpLookaheadDays = 30;   // Days of forward-looking events to export
input string InpCurrencies    = "";   // Comma-separated ISO currency codes, e.g. "EUR,USD" (blank = all)
input int    InpMinImportance = 3;    // 0=None 1=Low 2=Moderate 3=High (CALENDAR_IMPORTANCE_*)

void OnStart()
  {
   datetime now  = TimeTradeServer();
   datetime from = now - (datetime)InpLookbackDays * 86400;
   datetime to   = now + (datetime)InpLookaheadDays * 86400;

   // ...open CSV, write header (identical WriteCsvRow/CsvSafe helpers as
   // TransactionCostCollector.mq5, attached in full rather than repeated here)...

   // Blank InpCurrencies queries every currency in one unfiltered pass;
   // otherwise CalendarValueHistory() is called once per requested currency.
   // (Error handling omitted here; see the attached script.)
   string currencies[];
   int n_ccy = 0;
   if(InpCurrencies != "")
      n_ccy = StringSplit(InpCurrencies, ',', currencies);

   MqlCalendarValue values[];
   int total = 0;

   if(n_ccy == 0)
      total = CalendarValueHistory(values, from, to, NULL, NULL);
   else
     {
      for(int c = 0; c < n_ccy; c++)
        {
         MqlCalendarValue chunk[];
         int got = CalendarValueHistory(chunk, from, to, NULL, currencies[c]);
         if(got < 0)
            continue;
         int base = ArraySize(values);
         ArrayResize(values, base + got);
         for(int i = 0; i < got; i++)
            values[base + i] = chunk[i];
        }
      total = ArraySize(values);
     }

   int written = 0;
   for(int i = 0; i < total; i++)
     {
      MqlCalendarEvent event;
      if(!CalendarEventById(values[i].event_id, event))
         continue;
      if((int)event.importance < InpMinImportance)
         continue;

      MqlCalendarCountry country;
      string ccy = "";
      if(CalendarCountryById(event.country_id, country))
         ccy = country.currency;

      string key   = StringFormat("event_%05d", written);
      string value = TimeToString(values[i].time, TIME_DATE | TIME_MINUTES | TIME_SECONDS);
      WriteCsvRow(fh, "high_impact_events", key, value, ccy, CsvSafe(event.name));
      written++;
     }

   WriteCsvRow(fh, "status", "ok", "complete", "", "");
   FileClose(fh);
  }

The Python side is a single loader, returning exactly the shape filter_news_by_cost_model already expects:

def load_calendar_csv(csv_path: Path, *, server_tz: str) -> list[tuple[pd.Timestamp, str]]:
    """
    Event times in the CSV are trade-server time (TimeTradeServer()). server_tz is
    the IANA name of the server's clock and has no default; returned timestamps
    are timezone-aware UTC. Ambiguous or nonexistent DST-transition times raise.
    """
    df = pd.read_csv(csv_path)
    rows = df[df["section"] == "high_impact_events"]
    if rows.empty:
        raise KeyError(f"{csv_path} has no 'high_impact_events' section.")
    return [
        (pd.Timestamp(row["value"])
         .tz_localize(server_tz, ambiguous="raise", nonexistent="raise")
         .tz_convert("UTC"), str(row["unit"]))
        for _, row in rows.iterrows()
    ]

Event times from this collector are in trade-server time. server_tz is required and has no default, and the returned timestamps are UTC, so they can be passed to news_window_factor as they are. The contract is covered in Implementation Notes.


Implementation Notes

Loader Version Alignment

TransactionCostCollector.mq5 also changed since Part 14: a reader comment on the accompanying codebase's discussion thread pointed out that CopySpread() — the function the original script used for its entire spread distribution — returns the lowest spread registered within a bar's timespan, not the spread a trade actually crosses. The attached v3.00 script replaces it with tick-sampled spread via CopyTicksRange(), writing four independently weighted distributions instead of one spread_summary section; spread_exec_conditional, the prevailing quote at each execution-timeframe boundary, is the one to use for cost modeling.

get("spread_summary", spread_percentile) now raises KeyError immediately, since the section no longer exists. Falling back to it silently would be worse than an error, since spread_summary is exactly the bar-resolution statistic the refactor exists to fix. load_cost_model() now takes a spread_section argument, defaults to spread_exec_conditional, and raises a specific error distinguishing a pre-v3 CSV from any other missing-section cause:

# load_cost_model(): unchanged parameters/get()/status-guard omitted.
_KNOWN_SPREAD_SECTIONS = frozenset({
    "spread_tick_weighted", "spread_time_weighted",
    "spread_exec_conditional", "spread_bar_field",
})

def load_cost_model(
    csv_path: Path,
    spread_section: str = "spread_exec_conditional",
    spread_percentile: str = "p95_pips",
    # ...remaining parameters unchanged...
) -> TransactionCostModel:
    df = pd.read_csv(csv_path)
    # ...get() and the status-error guard are unchanged...

    if df[df["section"] == spread_section].empty:
        if not df[df["section"] == "spread_summary"].empty:
            raise KeyError(
                f"{csv_path} has 'spread_summary' but no {spread_section!r} -- "
                "this looks like a pre-v3 export (CopySpread(), bar "
                "resolution). Re-run TransactionCostCollector.mq5 v3+; do "
                "not substitute spread_summary."
            )
        raise KeyError(f"{csv_path} has no {spread_section!r} section.")

    spread_pips = float(get(spread_section, spread_percentile))
    # ...currency_base/currency_profit/currency_margin reads unchanged...

Swap-Mode and Sign Fix

The new script's swap_mode labels also track the SYMBOL_SWAP_MODE_* enum names more closely than the old ones, and name two modes the old script never labeled at all:

SYMBOL_SWAP_MODE_*

v1/v2 string

v3.00 string

POINTS points points
CURRENCY_SYMBOL currency currency_symbol
CURRENCY_MARGIN currency_mrgn currency_margin
CURRENCY_DEPOSIT currency_dep currency_deposit
INTEREST_OPEN interest_open interest_open
INTEREST_CURRENT interest_curr interest_current
REOPEN_CURRENT unknown (unhandled) reopen_current
REOPEN_BID unknown (unhandled) reopen_bid

Table 2. Swap-mode string rename between collector versions

swap_cost_frac's branch checks only recognized the old spellings, so a currency- or interest-mode swap now silently falls through to 0.0. There is no exception, only a swap cost of zero for any non-points-mode symbol. The fix accepts both spellings and, for the two reopen modes — which recompute swap by reopening the position at a new reference price each night rather than accruing a fixed per-night rate — raises instead of silently approximating, since no constant-rate model applies to them.

A third, unrelated regression: Part 14 already fixed the swap sign convention once, negating the rate so a debit produces a positive cost and a credit produces a negative one. The current codebase wraps every rate in abs() again, silently converting carry credits back into costs — caught only while tracing the swap-mode rename, not from any test failing on its own.

# Both v1/v2 and v3.00 spellings accepted, so a CSV from either
# collector version parses the same way.
_SWAP_CURRENCY_MODES = frozenset({
    "currency", "currency_mrgn", "currency_dep",                # v1/v2
    "currency_symbol", "currency_margin", "currency_deposit",  # v3.00
})
_SWAP_INTEREST_MODES = frozenset({
    "interest_open", "interest_curr", "interest_current",
})
_SWAP_DISABLED_MODES = frozenset({"unknown", "disabled_or_unknown"})
_SWAP_REOPEN_MODES   = frozenset({"reopen_current", "reopen_bid"})

def swap_cost_frac(self, entry_price: float, holding_days: float, side: int = 1) -> float:
    """
    Sign convention: negate the rate so a debit produces a positive
    cost and a credit produces a negative one -- do not wrap it in
    abs(), which silently turns every carry credit into a cost.
    """
    rate = self.swap_long_per_night if side >= 0 else self.swap_short_per_night
    nights = holding_days + (2 if holding_days >= 3 else 0)

    if self.swap_mode == "points":
        swap_price = -rate * self.point * nights
        return swap_price / entry_price if entry_price > 0 else 0.0

    elif self.swap_mode in _SWAP_CURRENCY_MODES:
        total_swap = -rate * self.lot_size * nights
        notional = entry_price * self.contract_size * self.lot_size
        return total_swap / notional if notional > 0 else 0.0

    elif self.swap_mode in _SWAP_INTEREST_MODES:
        nightly_rate = -rate / 100.0 / 365.0
        return nightly_rate * nights

    elif self.swap_mode in _SWAP_DISABLED_MODES:
        return 0.0

    elif self.swap_mode in _SWAP_REOPEN_MODES:
        raise ValueError(
            f"symbol={self.symbol!r} has swap_mode={self.swap_mode!r}. "
            "REOPEN_CURRENT/REOPEN_BID recompute swap by reopening the "
            "position at a new reference price each night; no fixed "
            "per-night rate applies. Confirm the mechanism with the "
            "broker before adding a case, or pass holding_days=0.0 if "
            "this symbol is only ever traded intraday."
        )

    raise ValueError(f"symbol={self.symbol!r} has unrecognized swap_mode={self.swap_mode!r}.")

The nights line approximates the triple-swap charge: a hold of three or more days is assumed to cross the triple-swap day and is billed two extra nights. Actual triple swap depends on which weekdays the position spans, the instrument, and the broker. The collector exports the symbol's triple-swap weekday (swap_3day) and load_cost_model() stores it as swap_triple_day, but swap_cost_frac does not use it. Treat the swap term as an approximation until the model counts the actual triple-swap days between entry and exit.

Validated against a synthetic v3.00 CSV covering four spread sections, both swap-mode spellings, a reopen_current case, and a positive carry-credit rate, alongside a synthetic pre-v3 CSV carrying only spread_summary. All four fixes passed: the sign convention correctly returns a negative cost for a credit and a positive cost for a debit, every v3 swap-mode spelling is recognized, the reopen modes raise instead of silently returning zero, and the pre-v3 CSV raises an informative KeyError rather than a generic one. These are synthetic-data checks. They confirm parsing and branch behavior; they do not validate the economics of the spread, swap, or news models against real broker data.

Timestamp Normalization

current_time and every entry in news_times must be UTC, but nothing in the original news_window_factor checked that. The call pd.Timestamp(current_time).tz_localize(None) strips whatever timezone label a timestamp carries without converting to a common reference. That is correct if every input is UTC. It is silently wrong for any timezone-aware timestamp in another zone.

# What tz_localize(None) does: strip the label, keep the wall-clock number
# What it does NOT do: convert to UTC first
pd.Timestamp("2026-01-01 07:00", tz="-05:00").tz_localize(None)   # -> 07:00, not 12:00

The function listed in Section 4 now calls a small helper instead. It converts timezone-aware inputs to UTC and treats naive inputs as UTC:

def _to_naive_utc(ts) -> pd.Timestamp:
    ts = pd.Timestamp(ts)
    if ts.tzinfo is not None:
        ts = ts.tz_convert("UTC")
    return ts.tz_localize(None)

This is worth singling out rather than applying universally, because a timezone mismatch produces a plausible-looking wrong number with no exception anywhere. The input type is unusually easy to get wrong when crossing a Python, pandas, and MQL5 boundary, and unusually hard to notice once wrong. The helper still trusts naive timestamps to be UTC, so a naive server-time timestamp would pass unnoticed.

The calendar collector is where this stops being abstract: its timestamps are trade-server time by MQL5's convention, not UTC. Making server_tz a required keyword-only argument of load_calendar_csv means the conversion cannot be skipped by omission, and the loader returns timezone-aware UTC. It does not verify that the zone is correct. A fixed-offset zone such as Etc/GMT-2 is right only for a server that does not observe daylight saving; many broker servers shift with it, so use the IANA zone that matches the server's clock changes, and confirm it with the broker.


Conclusion

Key takeaways:

  • Remaining risk budget and phase progress are distinct signals, not independent ones. Both derive from the same balance and P&L history. A good day late in a challenge is where they pull in opposite directions, and treating them as one signal misses that.
  • Multiplying modifiers compounds them; it does not select the strictest. Every modifier below 1.0 keeps reducing the size, so two moderate restrictions combine into a tighter one, and no modifier needs to know the others exist.
  • The same combined ceiling can come from opposite situations. The diagnostic columns, not the final number, are what tell them apart.
  • meets_min_trading_days is a fact about the account, and only the two-floor design needs it. The threshold and floors around it are strategy parameters, and none of them has been tested against pass rate here.
  • The news rule applies only in the funded stage and only to news correlated with the traded pair. The phase gate and the symbol filter implement those two limits. The size multiplier itself is a heuristic; it does not model the profit haircut or closing events.
  • Whether the news rule matters depends on the strategy's entry timing. In the illustrative simulation, timing-independent entries collided zero times in a year and deliberate post-release entries about one time in five. One simulated year is not evidence that the rule can be ignored.
  • Symbol-aware calendar filtering is needed for FX pairs. An unfiltered calendar adds false positives on every symbol, and the currency-based key does not extend cleanly to indices, metals, energy, or crypto CFDs.
  • Collectors and loaders are version contracts, not just file formats. A collector script can change its section names and its swap-mode spellings without warning, and a loader that assumes the old shape fails silently rather than loudly.
  • Timestamps carry a timezone contract. Calendar times are trade-server time. The loader now requires the server's timezone and returns UTC.

The three modifiers covered across this article and Part 2 — budget, phase-progress, news — complete PropFirmAwareSizer.size()'s current design. Part 4 moves to a different kind of constraint entirely: not on how large a position can be, but on how wide its stop-loss is allowed to sit, where the prop-firm daily loss ceiling meets the optimal trading rule search from Part 15.

Attached Files

 

File

Module

Description

 1. sizing.py MQL5/Files/afml.prop_firm derisking_factor, news_window_factor (with UTC normalization), and the rest of the sizing chain.
 2. transaction_costs.py MQL5/Files/afml.transaction_costs Extended with currency_base, currency_profit, currency_margin, correlated_currencies, and filter_news_by_cost_model (Section 5); spread_section support, the swap-mode vocabulary sets, and the restored sign-aware swap_cost_frac (Section 6); and load_calendar_csv with a required server_tz argument (Section 5), applied to the full Part 14 module rather than shown as isolated diffs.
 3. TransactionCostCollector.mq5 MQL5/Scripts v3.00: tick-sampled spread (CopyTicksRange()) in place of CopySpread(), four weighted distributions plus the bar-field audit, per Section 6.
 4. CalendarCollector.mq5 MQL5/Scripts Section 5's companion collector: exports high-impact calendar events to the same five-column CSV format via CalendarValueHistory().


Further Reading

  • López de Prado, M. (2018). Advances in Financial Machine Learning. John Wiley & Sons.
Attached files |
MQL5.zip (70.61 KB)
Last comments | Go to discussion (1)
Nikita.PMC
Nikita.PMC | 21 Nov 2026 at 11:54

An example for the derisking_factor. Account balance 100,000, target 8 per cent (i.e. 8,000), progress 90 per cent – account balance +7,200, 800 to go to the target. With a 1 per cent risk, a single stop-loss takes you back to 6,200, leaving 1,800 to go to reach the target. With a multiplier of 0.25, the same stop-loss costs 250, leaving 1,050 to go to reach the target.

But if the minimum number of trading days hasn’t yet been reached, the position size is still reduced, and you have to make up the days. The lower limit on the number of days is particularly relevant here; without it, the final days would be spent on trades that don’t move the position at all.

Regarding `news_window_factor`, the first thing I’d do is check the calendar’s time zone against the server time. The server is usually GMT+2 in winter and GMT+3 in summer. A 2-minute window with a one-hour offset simply won’t capture the news.

Foundation Models for Trading (Part III): Running a Generative AI Forecaster Inside MetaTrader 5 Foundation Models for Trading (Part III): Running a Generative AI Forecaster Inside MetaTrader 5
We demonstrate live forecast charting with Kronos in MQL5 and an evaluation pipeline designed to be look‑ahead‑safe. Deterministic dumps are scored per horizon against a random‑walk baseline (15,113 predictions), then fed to a simple Strategy Tester rule on EURUSD H1. The findings show no edge, and illustrate how a high threshold can yield a persuasive but low‑information backtest with very few trades.
How to Test and Customize Built-in MQL5 Programs: Envelopes with Alligator Strategy How to Test and Customize Built-in MQL5 Programs: Envelopes with Alligator Strategy
Envelopes define percentage boundaries around a moving average, but a boundary touch alone does not identify whether the market is trending or ranging. We build Envelope_Alligator_Strategy.mq5, a custom indicator that reads the built-in Envelopes and Alligator buffers. Ordered Alligator lines classify directional states; interwoven lines identify a neutral state. This context changes how envelope crossings are interpreted and produces testable, non-trading chart signals.
Neural Networks in Trading: Training Deep Spiking Models (SEW-ResNet) Neural Networks in Trading: Training Deep Spiking Models (SEW-ResNet)
We invite you to explore the SEW-ResNet framework, which allows you to build deep spiking models without degradation issues and with effective gradient management. In this article, we demonstrate how to implement a basic spiking neuron and its algorithms using MQL5.
Price Action Analysis Toolkit Development (Part 83): Building a Reusable Double-Bottom Pattern Library Price Action Analysis Toolkit Development (Part 83): Building a Reusable Double-Bottom Pattern Library
This recorder bridges visual labeling and systematic research in MQL5. After you position a rectangle, the EA extracts the candles it spans, derives candle geometry, normalizes OHLC values, assigns an ID, and saves the sample for reuse across sessions. The current category is the double bottom, and the module records the chosen sequence without enforcing a predefined pattern definition.