Request A Free Quote

Hedging EA: How Locking Strategies Work and What to Build Into One

Hedging EA lock on a GBP/USD candle chart: a buy at 1.2700, a sell at 1.2650 after a 50-pip fall, and the net result fixed at minus 500 dollars while price keeps moving

A hedging EA opens a position against a position you already hold. On MetaTrader that usually means a sell next to a buy on the same symbol, a setup traders call a lock. The idea is old and simple. When a trade goes against you, you stop the bleeding without taking the loss.

The arithmetic says something less comfortable. A lock doesn’t reduce a loss, it fixes it. From the moment the second position opens, price movement stops changing your result, and only the costs keep moving. Sooner or later one of the two legs has to be closed, and that close is a directional decision again, often made under more pressure than the original one.

That’s why we judge a hedging EA by its exit rules, not by how it opens the hedge. Below are the two things “hedging” means on MetaTrader, the four kinds of hedging EA, the numbers behind a lock, and the ways an EA can get out of one. At the end there’s a list of what to put in a specification if you want one built.

Two meanings of “hedging” on MetaTrader

The first meaning is an account setting. MetaTrader 5 supports two position accounting systems, netting and hedging, and the broker sets which one your account uses (MetaTrader 5 Help). On a netting account you hold one position per symbol, so a sell simply reduces, closes or reverses your buy. On a hedging account every trade opens its own position, and a buy and a sell on the same symbol can sit side by side. MetaTrader 4 always worked the second way, which is why most hedging EAs were written for it first.

The second meaning is the strategy: deliberately holding offsetting exposure. A same-symbol lock needs a hedging account. A hedge on a different, related instrument doesn’t, because two symbols are two positions even under netting.

An EA has to know which kind of account it’s on, and a well-written one checks on start-up. In MQL5 the account mode is one property call away. Code that assumes “one position per symbol” can close or modify the wrong ticket on a hedging account. Code that assumes it can open a lock simply nets the position away on a netting account.

US-regulated forex accounts can’t hold a same-symbol lock at all. Since 2009, NFA Compliance Rule 2-43(b) has required US forex dealers to offset positions on a first-in, first-out basis, which rules out opposite positions in the same pair in one account (OANDA). A lock EA built for an offshore MT4 account will fail there by design.

Four kinds of hedging EA

“Hedging EA” covers several designs with very different risk. Before you buy or order one, it helps to know which of these you’re actually looking at.

Same-symbol lock.Opens an opposite position on the same symbol when the trade moves against you by a set distance, or on a signal. Freezes the floating result and then manages the exit of both legs. Needs a hedging account.
Correlated-pair hedge.Offsets exposure on a related instrument, for example a long EUR/USD against a long USD/CHF. Works on netting accounts too. Its weak point is the ratio between the two legs and the moments when the correlation breaks.
Recovery hedge.Also sold as a hedge grid or zone recovery. Alternates buys and sells inside a price zone, increasing the lot each time, until the combined position reaches a profit target. The lot growth makes it a martingale in all but name.
Basket or exposure hedge.Watches the net exposure of several positions or strategies, say total USD exposure across pairs, and offsets or trims it when it crosses a limit. Closer to risk control than to a trading strategy.

The arithmetic of a lock

Take one trade on GBP/USD, where a 1.00 lot moves $10 per pip. You buy at 1.2700. Price falls 50 pips to 1.2650, and the EA opens a 1.00 lot sell there. At that moment your floating loss is $500. If price keeps falling, the sell gains exactly what the buy loses. If it rallies, the buy recovers exactly what the sell gives back. The $500 stays $500.

The arithmetic of a lock on GBP/USD: a 1.00 lot buy at 1.2700 and a 1.00 lot sell at 1.2650; below, the floating P&L of the buy alone falls past minus 1,000 dollars while the locked pair stays at minus 500 dollars

Three things do keep moving.

Spread and commissionYou pay them when each leg opens and again when it closes. MetaTrader 5 has a Close By operation that closes two opposite positions against each other, and according to MetaQuotes it saves one spread compared with closing them separately (MetaTrader 5 Help). A hedging EA that unwinds locks should use it.
Swap on both legsBoth positions are rolled over every night. The long and short swap rates are set by the broker and rarely cancel each other out, so in most cases a lock costs money for every day it’s held. A lock held for weeks can cost more than the spread on the original trade.
MarginBrokers can set a separate “hedged margin” for covered volume in the contract specification, and a value of zero means no margin is charged on it (MQL5). That makes a lock cheap to hold, which is exactly why locks tend to be held too long.

So a lock isn’t a stop loss you can undo. It’s a stop loss you haven’t finished yet. You’ve postponed the decision about the $500, and you’re paying a daily fee for the delay.

Getting out: how an EA resolves a lock

Every lock ends in one of two ways. Either both legs are closed together, which realises the frozen result plus costs. Or one leg is closed first, which turns the remaining position back into an ordinary directional trade. The second way is where hedging strategies earn or lose their money, so it deserves a picture.

Unlocking a GBP/USD lock: the sell leg is closed at 1.2580 for plus 700 dollars; if price recovers to 1.2700 the total is plus 700 dollars, and if the fall resumes to 1.2500 the total is minus 1,300 dollars against minus 500 with a plain stop

Continue the example. Price falls to 1.2580, a level you treat as support, and the EA closes the sell for +$700. You now hold only the buy from 1.2700, sitting at −$1,200. If price recovers to your entry, you close the buy for nothing and the whole episode ends at +$700 before costs. If the fall resumes to 1.2500 and the buy is stopped there, the buy loses $2,000 and the total is −$1,300. A plain stop at 1.2650 would have cost $500.

Neither outcome is a property of hedging. Both come from one decision at 1.2580: to bet that the fall was over. A hedging EA doesn’t remove that bet, it schedules it. What it can do is make the bet by a rule rather than by hope. These are the exit rules we see most often, and what each one trades away.

Exit rule How it works What it costs you
Close the profitable leg at a level The leg in profit is closed at a target, support or resistance. The other leg gets its own stop and target. Reopens full directional risk. Without a stop on the remaining leg, the loss can exceed the original stop.
Partial closes Part of one leg is closed at each step, shifting net exposure gradually in the direction of the move. More transactions and costs. Harder to test and to reason about.
Basket target All positions close together once their combined result, after costs, reaches a set amount. In a trend the target may never come. Needs a time or cost limit next to it.
Time or cost limit Both legs close when the lock has been held a set number of days or its swap has passed a set amount. Realises the frozen loss on purpose. That’s the point: it caps what the delay can cost.
Close By at the frozen result Both legs close against each other in one operation, paying one spread instead of two. Nothing beyond the loss you already had. It’s the stop loss you postponed.

Underneath these rules sits the bookkeeping, which is where many hedging EAs break. The EA has to know which tickets belong to which lock, survive a terminal restart without forgetting it, and never touch positions opened by you or by another EA. In practice that means its own magic number, a record of each lock that can be rebuilt from the open positions after a restart, and explicit handling of partial fills and requotes.

Correlated-pair hedges: the ratio is the hard part

A hedge on a second instrument only offsets the first if the sizes are right, and equal lots are rarely right. Two pairs move different distances in a day, and a pip is worth a different amount on each. A common starting point is to size the hedge by volatility and pip value:

hedge lots = main lots × (ATR of main × pip value of main) ÷ (ATR of hedge × pip value of hedge)

With illustrative numbers: EUR/USD moving 70 pips a day at $10 a pip, and USD/CHF moving 60 pips at about $11.40 a pip (a CHF pip converted to dollars). A 1.00 lot EUR/USD long is then offset by roughly 1.00 lot of USD/CHF long, because the two pairs usually move in opposite directions. Change the volatility and the ratio changes with it, which is why the EA should recalculate it rather than store a fixed number.

The bigger risk is the correlation itself. It’s measured on the past and can disappear in a day. On 15 January 2015 the Swiss National Bank dropped its EUR/CHF floor and USD/CHF fell by more than 10% within minutes. A long USD/CHF leg meant to hedge a long EUR/USD lost far more than the EUR/USD leg could ever have offset. A correlated-pair EA should check the current correlation before every new hedge and stop opening them when it falls below a threshold.

What hedging doesn’t fix

A trend against you.A lock holds the loss where it was, and costs keep adding to it. Every unlock in a strong trend is a bet against the trend. Locking and re-locking in the same move multiplies costs and decisions without changing the direction of the market.
Lot growth.Recovery hedges increase the lot at each step. With lots that double, the sixth step is 32 times the first. A move long enough to need step seven or eight usually ends in a margin call, however good the backtest looked before it.
Broker and regulator rules.Netting accounts can’t hold a lock, US accounts follow FIFO, and some brokers restrict hedging in their own terms. Check your account mode and terms before the EA trades real money.
Prop firm rules.Many prop firms forbid hedging across accounts, and some restrict it within one account. The rules differ by firm and change over time. We look at how firms treat automation in Automated Trading on Prop Firm Accounts.

Testing needs the same honesty. Run the EA in the Strategy Tester on a hedging account with real ticks, and include commission and swaps, since a lock’s costs are most of its story. Then make sure the test covers at least one strong one-way period for every symbol, the kind of move where a lock gets held for weeks. A backtest that only covers ranging markets will make any hedging strategy look safe.

What to put in a hedging EA specification

Whether you’re ordering an EA or reviewing one you’ve bought, these are the questions it has to answer. A missing line here usually turns into a gap in the code.

Item What to decide
Entry logic What opens the first position, on which symbols and timeframes.
Lock trigger Distance in pips or in ATR, a signal, or a time. Whether a lock can be opened more than once per trade.
Lock size Full, partial or by ratio. For a second instrument, how the ratio is calculated and how often.
Exit rules Which leg closes first and on what condition, the stop and target of the remaining leg, the basket target if any.
Limits Maximum number of open locks, maximum total lots, maximum days a lock may be held or swap it may cost.
Account handling What the EA does on a netting or FIFO account: refuse to start, or switch to a mode that works there.
Restart and recovery How the EA finds its own positions after a restart, and what it does if one leg was closed by hand.
News and weekends Whether to avoid opening locks before news or the weekend, when gaps can move both legs’ costs.
Logging A record of every lock and unlock with the reason, so live results can be compared with the backtest.

Building one with us

We write hedging EAs for MetaTrader 4 and MetaTrader 5 to the client’s own rules, from simple same-symbol locks to correlated-pair and basket logic. You talk directly with the developer who writes your code. Before any code is written we go through the lock and exit rules with you, because that’s where most specifications have gaps, and that first consultation is free.

Before it goes live, we test the EA with you in the Strategy Tester and on a demo account at the broker you plan to use, including a restart in the middle of an open lock. Bugs found after delivery are fixed at no extra cost. Since 2018 our team has completed over 3,000 development projects for traders in more than 120 countries.

Discuss your hedging EA →

Prefer to start from your platform? → MetaTrader 4 developers · MetaTrader 5 developers

FAQ

Does a hedging EA make a losing trade profitable?

No. A lock fixes the floating result at the moment it opens. Any later profit comes from closing one leg at the right time, which is a directional decision like any other, and the costs of holding both legs come off the result.

Can I run a hedging EA with a US broker?

Not a same-symbol lock. NFA Compliance Rule 2-43(b) requires US forex dealers to close positions first in, first out, which rules out opposite positions in the same pair in one account. A hedge on a different instrument can still work there.

What is the difference between hedging and netting accounts in MT5?

A netting account keeps one position per symbol, so an opposite trade reduces or reverses it. A hedging account keeps every trade as a separate position, so a buy and a sell on the same symbol can be open together. The broker sets the mode for each account.

Is a hedging EA the same as a martingale?

Not necessarily. A lock with fixed lot sizes isn’t a martingale. Recovery hedges that increase the lot after each step are, whatever they’re called, and carry the same risk of a margin call in a long one-way move.

Can I use a hedging EA on a prop firm account?

It depends on the firm. Many forbid hedging between accounts and some restrict it within one account. Read your firm’s current rules before you connect the EA.

Sources referenced in this article:

  1. MetaTrader 5 Help, Trading Principles: position accounting, netting and hedging systems: metatrader5.com
  2. MetaQuotes, MetaTrader 5 features hedging position accounting system (Close By, hedged margin): mql5.com
  3. MetaTrader 5 Help, Close By: metatrader5.com
  4. OANDA, The NFA FIFO rule and its challenges for expert advisors: oanda.com

Nordman Algorithms provides software infrastructure for trade automation and does not offer financial advice, trading signals, or managed trading services. This article is for informational and educational purposes only. Prices and results in the examples are illustrations with round numbers, not recorded trades, and exclude spread, commission and swap unless stated. An EA executes the rules it is given and does not adapt to market conditions outside them. Broker, regulator and prop firm rules differ and change over time. Trading leveraged instruments such as Forex, CFDs and futures carries a high level of risk and may not be suitable for all investors. Only risk capital should be used. Full Risk Disclosure