Net Profit Closing Martingale EA Logic Forex: How It Works

15 сентября 2026, 10:56
Andrey Kozak
0
18
Net Profit Closing Martingale EA Logic Forex: How It Works



The net profit closing Martingale EA logic Forex traders use is designed to close a group of open positions when their combined floating profit reaches a predefined target. Instead of evaluating each trade independently, the Expert Advisor calculates the net result of the entire Martingale basket, including winning trades, losing trades, commissions, swaps, and other applicable trading costs.

This approach is common in Forex grid and Martingale systems. A sequence may contain several losing positions and one or more profitable positions. The objective of net profit closing is to close the complete basket once the combined result reaches the configured profit threshold.

However, net profit closing is an exit mechanism, not a risk-management solution by itself. A basket can eventually close in profit while still exposing the trading account to substantial drawdown, margin pressure, and the possibility of a forced liquidation.

What Is Net Profit Closing in a Martingale EA?

Net profit closing is a basket-level exit rule.

A conventional take-profit setting may close one position when that individual trade reaches a specified profit. A net profit closing rule evaluates all positions managed by the EA and closes them together when their combined result satisfies a target.

For example, consider a basket containing three trades:

Trade Floating Profit/Loss
Buy 0.01 lot -$12
Buy 0.02 lot -$8
Buy 0.04 lot +$25
Combined result +$5

If the EA's net profit target is $5, the closing condition is satisfied, assuming the calculation includes all required costs and the actual net result is at least $5.

The important point is that the EA does not need every individual trade to be profitable. It evaluates the basket as a whole.

How Martingale Basket Logic Works

A typical Martingale EA follows a sequence similar to this:

  1. Open an initial position based on an entry signal.

  2. Monitor price movement and the open position.

  3. If price moves against the position by a configured distance, open an additional position.

  4. Increase the next lot size according to the selected multiplier or progression rule.

  5. Recalculate the basket's combined floating profit.

  6. Close all managed positions when the net profit target is reached.

  7. Reset the sequence and wait for a new entry condition.

A simplified lot progression may look like this:

Level Lot Size Multiplier
1 0.01
2 0.02 2.0
3 0.04 2.0
4 0.08 2.0

The actual progression does not have to be a classic doubling sequence. Some EAs use a multiplier such as 1.2 or 1.5, a fixed lot increment, or a custom progression.

The critical distinction is that the lot multiplier controls exposure, while net profit closing controls the basket exit.

Net Profit Closing Formula

A robust EA should calculate the net result of all positions included in the basket.

A simplified formula is:

Net Basket Profit = Sum of Floating Trade Profit + Swap + Commission + Other Applicable Costs

Depending on the platform and implementation, commissions and swaps may already be reflected in the position's profit-related fields or may need to be added separately. The developer must verify the exact accounting behavior of the trading platform and broker.

For a basket containing positions 1 1 through n n:

P n e t = i = 1 n P i + S + C + O P_{net} = \sum_{i=1}^{n} P_i + S + C + O

Where:

  • P i P_i = floating profit or loss of position i i

  • S S = total swap adjustment

  • C C = total commission adjustment

  • O O = other applicable costs or adjustments

  • P n e t P_{net} = combined net basket result

The closing condition can then be represented as:

P n e t P t a r g e t P_{net} \geq P_{target}

If the net basket profit is equal to or greater than the configured target, the EA sends close requests for the positions belonging to that basket.

Example: Net Profit Closing in Action

Suppose a Martingale EA manages a group of EUR/USD buy positions.

Position Lot Size Floating P/L
Buy 0.01 0.01 -$18
Buy 0.02 0.02 -$10
Buy 0.04 0.04 +$21
Buy 0.08 0.08 +$35
Gross floating result +$28

Assume the basket has:

  • Commission: -$3

  • Swap: -$1

  • Net profit target: $20

The calculation becomes:

Gross Floating Profit:  +$28
Commission:              -$3
Swap:                    -$1
--------------------------------
Net Basket Profit:       +$24

Because $24 ≥ $20, the EA's net profit closing condition is met.

The EA should then attempt to close all positions associated with that basket.

Why the Basket Can Close Even with Losing Trades

The larger positions in a Martingale sequence have a greater impact on the combined result. In the example above, the profitable positions offset the earlier losing positions.

This is the central concept behind basket-based recovery logic. The EA does not require the original trade to return to its entry price if the combined positions have already reached the target.

Nevertheless, this mechanism does not eliminate the underlying risk. Larger positions also increase the speed at which losses and margin requirements can grow.

Net Profit Closing vs. Individual Take Profit

These two exit methods serve different purposes.

Feature Individual Take Profit Net Profit Closing
Evaluation One trade Entire basket
Exit trigger Position-specific profit Combined net profit
Losing trades allowed at exit Usually irrelevant to that trade Yes, if basket is profitable
Typical use Single-position strategies Grid and Martingale systems
Calculation scope Individual order or position All selected managed positions

For a non-Martingale strategy, individual take profit may be sufficient. For a basket-based strategy, net profit closing is often more aligned with the structure of the system.

What Positions Should Be Included in the Calculation?

This is one of the most important implementation decisions.

An EA should not blindly sum every open position in the trading account. The calculation should identify which trades belong to the specific strategy or basket.

Common filters include:

  • Magic number

  • Trading symbol

  • Position direction

  • Strategy identifier

  • Basket or cycle identifier

  • Account or portfolio scope

  • Trade comment, where appropriate

For example, an EA running on EUR/USD should generally avoid including unrelated GBP/USD positions or trades opened manually by the trader.

A typical basket scope might be defined as:

Include position if: MagicNumber == EA_Magic AND Symbol == CurrentSymbol AND Position belongs to the active basket

For hedging accounts, the EA may manage multiple positions on the same symbol. For netting accounts, the platform may represent exposure differently, so the implementation must account for the relevant MT5 position model.

Basic Pseudocode for Net Profit Closing

The following pseudocode illustrates the general concept. It is not a complete production-ready EA and does not include broker-specific execution handling.

function CalculateBasketNetProfit():
    totalProfit = 0

    for each open position:
        if position belongs to this EA basket:
            totalProfit += position floating profit
            totalProfit += applicable swap
            totalProfit += applicable commission

    return totalProfit


function CheckBasketClose():
    netProfit = CalculateBasketNetProfit()

    if netProfit >= NetProfitTarget:
        CloseAllBasketPositions()

A production implementation should also handle:

  • Partial close failures

  • Trade context or execution errors

  • Requotes and requotes-related behavior where applicable

  • Slippage and execution deviation

  • Market closure

  • Spread widening

  • Multiple close attempts

  • Duplicate execution events

  • Basket state after a terminal restart

  • Positions added while the basket is being closed

Important: Floating Profit Is Not the Same as Guaranteed Realized Profit

A basket may temporarily show a positive floating net profit, but that value can change before all close orders are executed.

This can happen because of:

  • Price movement

  • Spread changes

  • Slippage

  • Commission differences

  • Swap updates

  • Execution delays

  • Partial fills or rejected orders

For this reason, a well-designed EA should not assume that a successful close request automatically means the entire basket has been closed at the target.

The system should verify the resulting account and position state after sending close orders.

Net Profit Target: Fixed Amount or Percentage?

There are several ways to define a basket profit target.

1. Fixed Currency Amount

Example:

NetProfitTarget = $10

The EA closes the basket when the net result reaches $10.

Advantages:

  • Easy to understand

  • Simple to configure

  • Predictable nominal target

Limitations:

  • Does not automatically adapt to account size

  • A $10 target has different significance on a $500 account and a $50,000 account

2. Percentage of Account Balance

Example:

NetProfitTarget = 0.5% of balance

If the account balance is $10,000:

Target = $10,000 × 0.005 = $50

Advantages:

  • Scales with account size

  • More suitable for portfolio-level configuration

Limitations:

  • The target changes as the account balance changes

  • The implementation must define whether the calculation uses balance, equity, or another reference

3. Percentage of Equity

An equity-based target may be calculated from the current or starting equity of the basket.

However, the EA developer must define the reference value carefully. If the reference equity changes continuously, the target may move in a way that makes the strategy difficult to evaluate.

4. Weighted Profit Target

Some EAs use a target based on the number of positions, total lots, or basket exposure. For example, the target may increase as the basket grows.

This is more complex and should be documented clearly because the closing behavior may differ significantly from a fixed target.

Risk Controls That Should Accompany Net Profit Closing

Net profit closing should not be the only protective mechanism in a Martingale EA.

A basket can remain negative for an extended period, and increasing position sizes can create significant exposure before the recovery target is reached.

Important risk controls include:

Maximum Martingale Levels

Limit the number of additional positions in a sequence.

MaxLevels = 5

Once the limit is reached, the EA should follow a clearly defined policy rather than continuing to increase exposure indefinitely.

Maximum Lot Size

Set an absolute cap on the size of any individual position.

MaxLot = 0.10

This does not eliminate risk, but it prevents unlimited lot escalation.

Maximum Total Exposure

A total-lot or notional-exposure limit can restrict the combined size of all positions in the basket.

Equity Stop

An equity stop can disable new trades or close positions when account equity falls below a defined threshold.

For example:

EquityStopPercent = 20%

The exact interpretation must be specified: it could mean a 20% drawdown from starting equity, balance, or a high-water mark.

Maximum Drawdown Limit

A drawdown limit can be used to stop the strategy after a predefined loss level.

Spread Filter

Avoid opening additional positions when spreads exceed the configured maximum.

This is particularly relevant around market opens, news releases, rollover periods, and periods of low liquidity.

Trading Session Filter

The EA may restrict entries to defined trading sessions and avoid adding positions during periods when execution conditions are less favorable.

Margin-Level Protection

The EA should monitor free margin and margin level. A basket that is theoretically capable of recovering may still be unable to survive long enough to reach the target.

Why Net Profit Closing Does Not Make Martingale Safe

The phrase “net profit closing” can sound reassuring, but it describes how trades are exited—not whether the strategy has a favorable risk profile.

Martingale systems typically increase exposure after adverse price movement. If the market continues moving in one direction, the basket may accumulate larger positions while its floating loss grows.

A winning basket can therefore coexist with a severe tail-risk profile.

The main risks include:

  • Rapid lot-size growth

  • Margin exhaustion

  • Large floating drawdown

  • Trend persistence

  • Volatility expansion

  • Gaps and slippage

  • Trading restrictions

  • Broker execution limitations

  • Correlation between multiple baskets

  • Failure to close all positions at the expected price

A backtest that shows frequent profitable basket closures does not, by itself, establish that the EA is robust.

Backtesting Net Profit Closing Logic

When testing a Martingale EA, evaluate more than total net profit.

Important metrics include:

  • Maximum drawdown

  • Maximum equity drawdown

  • Largest basket loss

  • Maximum number of open positions

  • Maximum lot size reached

  • Maximum total exposure

  • Longest recovery sequence

  • Number of baskets closed in profit

  • Number of baskets stopped by risk controls

  • Margin level during adverse periods

  • Profit factor

  • Recovery factor

  • Average basket duration

  • Worst historical and simulated losing sequence

Test Different Market Conditions

A useful test should include:

  • Trending markets

  • Range-bound markets

  • High-volatility periods

  • Low-volatility periods

  • News-driven price movements

  • Spread-widening conditions

  • Different broker execution assumptions

A strategy that performs well in a narrow historical period may behave differently when market structure changes.

Use Stress Testing and Monte Carlo Analysis

Monte Carlo analysis can help evaluate how the strategy responds to variations in trade order, slippage, spreads, and losing-sequence frequency.

For Martingale systems, the length and severity of adverse sequences are particularly important. A small change in the distribution of losses can have a disproportionately large effect on required capital and drawdown.

Common Implementation Mistakes

Mistake 1: Calculating Gross Profit Instead of Net Profit

If commissions and swaps are excluded, the EA may close a basket that appears profitable but is actually below the intended net target.

Mistake 2: Including Unrelated Trades

Summing all positions on the account can cause the EA to close trades that belong to another strategy or manual trading activity.

Mistake 3: Closing Only the Last Position

A basket-level target should generally trigger the closure of all positions assigned to that basket—not only the most recent trade.

Mistake 4: Ignoring Partial Close Failures

One close request may succeed while another fails. The EA should re-evaluate the remaining positions and handle the incomplete closure safely.

Mistake 5: Starting a New Basket Too Early

If the EA starts a new cycle before confirming that the previous basket is fully closed, it may unintentionally overlap sequences and increase exposure.

Mistake 6: Using an Unbounded Lot Multiplier

A mathematical progression can become operationally impossible when margin, maximum lot size, or broker limits are reached.

Mistake 7: Treating Backtest Results as a Guarantee

Historical performance is not proof of future results. A Martingale EA is especially sensitive to market conditions that may not appear frequently in a limited backtest.

Recommended Configuration Philosophy

There is no universally correct set of Martingale EA parameters. The appropriate configuration depends on the account, instrument, broker conditions, trading timeframe, and risk tolerance.

A disciplined configuration process should include:

  1. Define the basket scope.

  2. Choose a transparent lot-sizing rule.

  3. Set a maximum number of levels.

  4. Set a maximum lot size.

  5. Define the net profit calculation precisely.

  6. Include relevant trading costs.

  7. Configure an equity or drawdown protection mechanism.

  8. Test on historical data.

  9. Perform stress testing.

  10. Validate behavior on a demo account.

  11. Monitor live execution if the EA is deployed with real funds.

The purpose of these controls is not to guarantee profitability. It is to make the strategy's behavior measurable, bounded, and easier to audit.

Frequently Asked Questions

What does net profit closing mean in a Martingale EA?

Net profit closing means the EA closes a group of managed positions when their combined net floating profit reaches a predefined target. The calculation may include trading profit, commission, swap, and other applicable costs.

Does net profit closing close all trades?

It should close all positions included in the defined basket. It should not automatically close unrelated trades unless the EA is explicitly designed to manage the entire account or portfolio.

Can a Martingale EA close a basket with losing trades?

Yes. A basket can close with some losing positions if the combined result of all positions reaches the net profit target.

Is net profit closing safer than individual take profit?

Neither method is inherently safe. Net profit closing is better suited to basket-based strategies because it evaluates combined exposure. The overall risk still depends on position sizing, market conditions, margin, and protective limits.

Should commission and swap be included?

If the goal is to close at a true net profit, applicable commissions, swaps, and other costs should be accounted for. The exact implementation depends on how the trading platform exposes these values.

Can this logic be implemented in MT4 and MT5?

Yes. The concept can be implemented in both MetaTrader 4 and MetaTrader 5. However, the order and position models differ, so the implementation must account for the platform's execution and position-management architecture.

Conclusion

The net profit closing Martingale EA logic Forex traders use is a basket-management mechanism that closes multiple positions when their combined net result reaches a configured target. It is particularly relevant to grid and Martingale EAs, where individual positions may have different profit and loss values.

The core calculation is straightforward:

Net Basket Profit = Combined Trade P/L + Swap + Commission + Other Applicable Costs

When the result reaches the target, the EA attempts to close the basket.

The more difficult part is not the formula—it is managing the risk created by the Martingale progression. A reliable implementation should combine net profit closing with maximum levels, lot limits, exposure controls, equity protection, execution-error handling, and thorough stress testing.

Net profit closing can define when a basket exits. It cannot remove the market risk inherent in the position-sizing strategy.

Use the closing logic to make the EA's behavior explicit and testable—not as a substitute for risk management.