Job finished
Specification
I need an MT5 Expert Advisor (MQL5) that works as a portfolio-level hedge supervisor for my gold grid EAs.
Key idea:
The EA will NOT open normal trading positions. It will only:
– Monitor account margin level.
– When margin level drops below a defined threshold (for example 250%), open a hedge position in the opposite direction of my net exposure.
– Use the hedge profit to “pay off” the oldest losing trade.
– If the market reverses and my grids recover, close the hedge at break-even (hedge loss offset by grid profit) and let the grids continue normally.
This EA will run on one chart only and manage risk for the whole portfolio (multiple XAU pairs and multiple magic numbers).
Platform and account
– MetaTrader 5
– Hedging account (not netting)
– Symbols mainly XAU pairs (XAUUSD, XAUJPY, XAUEUR etc.)
– Multiple grid EAs already running, each with its own magic number
Logic – high level
- The EA runs on one chart (any symbol).
- On every tick it reads:
– Balance, Equity, Margin, MarginLevel%. - It builds a list of “protected trades”:
– Only trades whose symbol is in a user-defined list (e.g. XAUUSD,XAUJPY,XAUEUR).
– Only trades whose magic is in a user-defined list (e.g. 1001,1002,1003).
– It must exclude its own hedge trades (separate hedge magic number).
Hedge activation (when there is no active hedge)
– If MarginLevel < MarginLevel_Trigger (for example 250%) and there is at least one losing trade in the protected set:
- Find the “oldest losing trade” (Profit < 0, earliest open time).
- Decide the hedge symbol:
– Either the same symbol as that oldest losing trade, or a master symbol such as XAUUSD (user input). - Calculate exposure:
– Option 1 (BY_NET_EXPOSURE): sum all buy lots minus sum all sell lots of protected trades and take the absolute value.
– Option 2 (BY_OLDEST_TRADE): use only the lot size of the oldest losing trade. - Hedge lot size:
– TargetHedgeLot = exposure_lots × HedgeFactor (e.g. 0.30).
– Calculate MaxLotByMargin based on FreeMargin, Margin per lot, and a SafetyFactor (e.g. 0.7 so we do not use all free margin).
– HedgeLot = min(TargetHedgeLot, MaxLotByMargin, MaxHedgeLot).
– If HedgeLot < MinHedgeLot (e.g. 0.01), then do not open a hedge. - Hedge direction:
– Always opposite to the main exposure (or opposite to the oldest losing trade if using that mode). - Open one market hedge position with a separate hedge magic number.
- Only one hedge position can exist at any time.
Hedge management (when a hedge is active)
There are two main behaviours:
A) Recoup oldest loser (trend continues against the grids)
– Rebuild the protected trades list.
– Find all losing trades (Profit < 0). If none exist, skip recoup and go to neutralisation logic.
– Select the oldest losing trade.
– Let:
– hedge_profit = profit of the hedge (money, can be positive or negative).
– oldest_profit = profit of the oldest losing trade (negative).
– Recoup rule:
– If hedge_profit + oldest_profit ≥ Recoup_Threshold (usually 0):
– Close the hedge position.
– Close that oldest losing trade.
– Reset internal state (no active hedge).
– Respect a cool-down time between actions (e.g. 60 seconds) so the EA does not over-trade.
Result: the hedge has effectively “paid for” the oldest loser, reducing grid exposure and improving margin.
B) Neutralise hedge (market reverses in favour of the grids)
– Calculate total_grid_profit = sum of Profit for all protected trades (can be overall positive when grids are recovering).
– Optionally require MarginLevel to be above a buffer (e.g. Neutralise_Margin_Buffer = 260) to avoid neutralising too early.
– Neutralisation rule:
– If hedge_profit + total_grid_profit ≥ Neutralise_Threshold (usually 0):
– Close the hedge position only.
– Do NOT close any grid trades.
– Reset internal state.
Result: the hedge is removed at or near break-even (its loss is offset by the grid profit), and the grid trades are left to reach their normal take-profit.
C) Optional hedge stop-loss
– If hedge_profit ≤ -Max_Hedge_Loss (if this input is > 0), close the hedge as an emergency stop, then reset state.
Cooldown and stability
– The EA must use a minimum time between actions (SecondsBetweenActions) to avoid opening or closing multiple trades too fast during spikes.
– It must handle cases where:
– The user manually closes trades or the hedge.
– The broker rejects an order (log the error and continue gracefully).
Inputs (example list)
– MarginLevel_Trigger (double, e.g. 250.0).
– Neutralise_Margin_Buffer (double, e.g. 260.0 or 0 to disable).
– Include_By_Symbol (string, comma separated).
– Include_By_Magic (string, comma separated).
– Hedge_Sizing_Mode (enum: BY_NET_EXPOSURE or BY_OLDEST_TRADE).
– HedgeFactor (double, e.g. 0.30).
– MaxHedgeLot (double).
– MinHedgeLot (double).
– Hedge_Symbol_Mode (enum: SAME_SYMBOL or MASTER_SYMBOL).
– Master_Hedge_Symbol (string, e.g. XAUUSD).
– SafetyFactor (double, e.g. 0.7).
– Max_Hedge_Loss (double, 0 = disabled).
– SecondsBetweenActions (integer, e.g. 60).
– Recoup_Threshold (double, usually 0.00).
– Neutralise_Threshold (double, usually 0.00).
– Hedge magic number (integer, separate from all grid EAs).
– Enable_Logging (bool).
Requirements for the code
– MQL5, clean and well commented.
– No DLLs.
– Must work in the MT5 Strategy Tester and on live trading.
– Use standard CTrade / trade classes and proper error handling.
– Must correctly support hedging accounts.
– Should be efficient enough to run on every tick with multiple symbols and positions.
Deliverables
– Source code (.mq5) and compiled file (.ex5).
– Brief note explaining how to set:
– Margin trigger
– HedgeFactor
– Symbols list
– Magic numbers
– Optional: basic Strategy Tester file or screenshots to prove the EA compiles and runs.
Please only apply if you have experience:
– Coding portfolio-level EAs that manage multiple symbols and magic numbers.
– Working with margin calculations and hedge logic.
– Working with gold (XAU) and high-volatility instruments is a plus.
–––––––––––––––––––––
SHORT “MUST-HAVE” LIST (OPTIONAL)
–––––––––––––––––––––
You can paste this either at the top or in the “Requirements” field:
– MT5 EA (MQL5), hedging account, no DLLs.
– One EA on one chart, monitoring margin level for whole account.
– Triggers when MarginLevel < 250%.
– Opens one hedge position (partial lot size, based on exposure and free margin).
– Uses hedge profit to close oldest losing trade at break-even (close hedge + that trade together).
– If market reverses and grids recover, closes hedge at break-even (hedge loss offset by grid profit), leaving grid trades open.
– Works across multiple XAU symbols and multiple magic numbers.
– Clean, robust code with comments and error handling.
If you want, I can also help you write a short first message to the devs once you start getting proposals (for example, how to check they actually understand the logic).