Position Closure Management MT5
- Utilities
- Version: 1.40
- Updated: 7 March 2026
- Activations: 10
NOHEDGE — Automated Hedge Manager and Risk Controller for MetaTrader 5
A close-only utility that never opens a trade. It resolves the buy/sell pairs you already carry, at zero spread, across your entire account.
OVERVIEW
Running grid, martingale or manual hedging strategies means you constantly carry open buy/sell pairs that need to be resolved at exactly the right moment — before the spread widens at rollover, before a news spike blows your account, or exactly at your daily profit target. Doing that manually is slow, error-prone and stressful.
NOHEDGE automates the entire process. It scans every tick, matches opposing buy/sell pairs across your account and closes them with MT5's native CloseBy mechanism, which settles both sides in a single server transaction at zero spread cost. Partial-volume matching is fully supported, so even complex multi-lot grids are unwound cleanly.
One EA, one chart, full account scope: NOHEDGE monitors and controls all symbols simultaneously from whatever chart you attach it to.
FEATURES
Zero spread on pair closings
Most close approaches call PositionClose() twice, once per leg, and pay the full spread twice. NOHEDGE uses the MT5 function CloseBy(), which settles both legs in one server request at zero spread. On gold or volatile pairs with a 30-50 point spread that is real money over hundreds of closes. Partial-volume matching handles any lot-size combination, with automatic fallback to PositionClose() for brokers without CloseBy support.
Master switch and safe defaults
EnableEA defaults to false, so not a single trade can be closed until you activate it. That makes NOHEDGE safe to attach to a live account for observation first: dashboard, panic buttons and all visual elements stay fully active while the automation is paused.
Live dashboard panel [new in v1.4]
An on-chart panel shows buy and sell count with total volume, P/L per side in real time, net P/L across all positions, daily P/L with an animated progress bar between loss limit and profit target, and the active filter status for rollover, spread, CloseBy mode and anti-loop. It refreshes every 2 seconds.
Accurate daily P/L with target and loss limit
Many tools track only the floating P/L of open positions. NOHEDGE adds every deal already realised that day before comparing against your target, so no close is triggered by an uncounted loss and no limit is missed because earlier profits were ignored. When daily P/L reaches the target or drops to the limit, the whole account is closed automatically, broker-accurate rather than estimate-based.
Three one-click panic buttons, always live
Three permanent on-chart buttons cover CLOSE ALL, CLOSE PROFIT ONLY and CLOSE LOSS ONLY. Dashboard, rollover guard and spread filter never disable them: even with EnableEA false or the rollover window active they fire immediately, and panic close deliberately bypasses the anti-loop cooldown so every position stays reachable. They centre horizontally by default and reposition themselves when the chart is resized.
Anti-loop protection for grid EAs
Grid and martingale EAs reopen positions the instant they are closed, and without a cooldown that turns into a destructive cycle that burns through equity in seconds. The ring-buffer cooldown runs at O(1) performance and blocks re-closing the same symbol for a configurable window, five minutes by default, then clears itself.
Rollover protection and spread filter
A configurable quiet window, 23:55 to 00:10 by default, suspends automated closing around the daily swap rollover, with three behaviours: postpone, close regardless, or close selectively by each symbol's spread. It applies separately to hedge closing, daily limits, time-based close and panic buttons. A per-symbol spread check also runs before every close attempt, with separate thresholds for standard pairs and for crypto and XAU, optionally active outside the rollover window too.
Cross-symbol hedging
No other basic close manager on the MQL5 Marketplace detects hedges across different symbols. NOHEDGE pairs a EURUSD buy with a GBPUSD sell — common in correlation-based strategies and basket grids — and closes them together with full partial-volume matching. Unpaired single positions are processed in the same pass when CloseSinglePositions is active.
Time-based closing and trading day filter
A forced close can be scheduled at a specific server time on individually selectable weekdays, covering all positions, buy only or sell only, with optional exclusion of crypto and XAU. Ideal for a Friday evening close before the weekend gap. Automated hedge closing has its own independent per-weekday switch.
Closing priority
Four close-order modes are available: newest first, oldest first, most profitable first and least profitable first, applied consistently across pair closing, single-position closing and cross-symbol mode.
Broker-grade error handling
Retry logic with exponential backoff, trade.ResultRetcode() for accurate broker rejection codes instead of the unreliable GetLastError(), specific error messages for every known TRADE_RETCODE, and automatic fallback to direct close when CloseBy is unavailable — all production-tested on live accounts running 24/7 on a VPS.
Multi-instance, multi-strategy
The magic-number filter restricts all operations to positions carrying a given magic number. Chart A can manage your grid EA with MagicNumber 1001 while chart B manages your scalper with MagicNumber 2002 — same account, fully independent, no conflicts.
Layout control and position markers
Independent PanelTopOffset and ButtonTopOffset inputs push dashboard and panic buttons down from the chart top separately [new in v1.4], for brokers whose toolbars overlap the chart header. Arrow markers mark every open position, green for buy and red for sell, optionally limited to the current symbol.
PARAMETERS
Every parameter ships with a working default. The only one you must change is EnableEA.
Master switch. EnableEA (false) is the master on/off; false means monitoring mode with dashboard and buttons active and no automated closing.
Hedge closing. EnableHedgeClosing (true) enables automatic hedge pair detection and closing. CloseOrder (newest first) chooses between newest, oldest, most profitable and least profitable. CloseOnlyMagic (false) restricts management to positions matching MagicNumber (12345). UseDirectClose (false) uses PositionClose instead of CloseBy for brokers without CloseBy support. MaxPositionsPerCycle (5) caps positions closed per tick to limit server load. MaxRetries (3) and RetryDelay (200 ms, doubling with each attempt, capped at 1 s) govern broker rejections, and VerboseLogging (false) enables detailed journal logging.
Daily profit and loss limits. EnableDailyLimits (true) activates the system. DailyProfitTarget (+1000.0) and DailyLossLimit (-500.0) are set in account currency and close all positions when daily P/L reaches or drops to them. DailyLimitBehavior (respect rollover) covers a limit hit inside the rollover window: postpone, close regardless or selective. CryptoHandling (always close) defines how crypto and XAU are treated when a limit triggers.
Anti-loop protection. PreventTradeLoop (true) locks a symbol after a close to prevent cycling with grid EAs, and TradeLoopCooldown (300 s) sets how long it stays locked, implemented as a ring buffer with O(1) lookup.
Cross-symbol and single positions. CrossSymbolClose (false) matches buy and sell across different instruments. CloseSinglePositions (false) also closes unpaired positions, independent of the daily limits, with SinglePosMaxCount (5) as the maximum per cycle. MinimumLotSize (0.01) ignores positions below that volume.
Trading day filter. MondayEnabled through SundayEnabled switch the EA per weekday; Monday to Friday true, Saturday and Sunday false.
Rollover protection. EnableIgnoreTime (true) activates the quiet window, defined in server time by IgnoreStartHour (23), IgnoreStartMinute (55), IgnoreEndHour (0) and IgnoreEndMinute (10).
Spread filter. CheckSpreadInIgnoreTime (true) extends the spread check outside the rollover window. MaxAllowedSpread (5.0 points) applies to standard pairs such as forex and indices, CryptoMaxSpread (25.0 points) to crypto and XAU, and CryptoPrefix holds the comma-separated prefixes such as BTC and ETH identifying those instruments.
Time-based closing. EnableTimeBasedClosing (false) is the master switch for scheduled closing at CloseHour (17) and CloseMinute (0) in server time. CloseOnlyForex (true) excludes crypto and XAU, CloseBuyOnly (false) and CloseSellOnly (false) restrict it to one direction. TimeBasedCloseBehavior (respect rollover) decides whether the rollover window is respected or overridden, and ClosingMon to ClosingSun configure each weekday individually, defaulting to Friday only.
Panic buttons. EnablePanicButton (true) shows the emergency close buttons. ButtonWidth (210 px), ButtonHeight (35 px) and ButtonFontSize (7) control their size, ButtonRightMargin (0) centres them horizontally while any higher value is a fixed pixel distance from the right edge, and ButtonTopOffset (10 px) their distance from the chart top. ButtonColor (red), ProfitButtonColor (green), LossButtonColor (crimson) and TextColor (white) define the appearance, and PanicButtonBehavior (close regardless) decides whether a panic close respects the rollover window.
Info panel. EnableEAComment (true) shows the live dashboard. PanelInfoWidth (480 px) scales the whole internal layout, PanelTopOffset (25 px) sets the distance from the chart top independently of the buttons, CommentRefreshSeconds (2 s) is the refresh interval, and CommentBgColor (80,80,80) plus CommentFontSize (7) give full RGB and font control.
Position markers. ShowPositionMarkers (true) draws an arrow per open position, ShowOnlyCurrentSymbol (true) limits them to the chart symbol, and BuyMarkerColor (SeaGreen), SellMarkerColor (Crimson) and MarkerSize (8) define their look.
INSTALLATION
Copy the compiled .ex5 file into the MQL5 Experts folder of your MT5 data folder, then restart MetaTrader 5 or press F5 to refresh the Navigator. Drag the EA onto any chart; the chart symbol does not matter, because NOHEDGE manages all account symbols by default. In the EA properties enable Allow automated trading and click OK. Dashboard and panic buttons appear immediately.
Set EnableEA to true to activate automated closing. Until you do, the EA runs in observation mode and is safe to use on a live account. Then set DailyProfitTarget and DailyLossLimit to your account size, switch EnableDailyLimits to true, and adjust IgnoreStartHour and IgnoreEndHour to your broker's swap rollover time; the default of 23:55 to 00:10 server time covers most brokers.
If your broker's toolbar overlaps the panel or the buttons, adjust PanelTopOffset and ButtonTopOffset. For multi-strategy setups, run a second instance on another chart with a separate MagicNumber filter.
IMPORTANT NOTES
Hedge account required. NOHEDGE closes buy/sell pairs by ticket, so both legs must exist as separate positions. That is only possible on hedge accounts. Netting accounts merge opposing positions immediately and cannot be managed.
AutoTrading must be enabled. The AutoTrading button in the MT5 toolbar must be green and Allow automated trading must be checked in the EA properties, otherwise no close operation can execute.
The EA never opens trades. It only closes what already exists and carries zero directional risk of its own. Because EnableEA defaults to false, nothing is closed until you activate it, which prevents unexpected closes on accounts that already have positions open.
Panic buttons bypass the guards. PanicButtonBehavior defaults to CLOSE_REGARDLESS, so the buttons execute even during the rollover window or under high spread; switch it to RESPECT_IGNORE_TIME if rollover protection should block panic closes too. The anti-loop cooldown never blocks them either.
The spread filter uses points, not pips. MaxAllowedSpread and CryptoMaxSpread are broker points as returned by SYMBOL_SPREAD. On a 5-digit broker, 5 points equal 0.5 pip for forex, and 50 points are 50 points for gold. Verify your broker's spread unit before setting these values.
Commission accuracy. Daily P/L and position P/L include profit, swap and commission, retrieved from the deal history instead of the deprecated POSITION_COMMISSION property, which keeps limit enforcement accurate even on commission-heavy ECN accounts.
COMPATIBILITY
MetaTrader 5 from build 3000 upwards, written in MQL5, for hedge accounts only; MT5 netting accounts are not supported. All instruments work, including forex, metals such as XAU and XAG, indices, crypto, energy and CFDs, and any timeframe works because NOHEDGE manages the account, not the chart. Any account size is fine, with DailyProfitTarget and DailyLossLimit set in your account currency. AutoTrading must be enabled in the terminal and in the EA properties, and a VPS with a stable broker connection is recommended for 24/7 operation and reliable rollover protection. A one-month rental is available alongside the full purchase.
Version 1.40 | fi.con Investment Group | MQL5 Marketplace
