Designing a Gold Trading EA with Basket Management, Prop Firm Protection and an OCO News Engine
1. Introduction
Automated trading systems are often described mainly through their entry logic: when to buy, when to sell, and where to place a Stop Loss or Take Profit.
In a production-oriented Expert Advisor, however, generating a valid signal is only one part of the problem.
Before an order is sent, the program may also need to determine whether the current spread is acceptable, whether account exposure is already too high, whether a drawdown limit is approaching, whether a high-impact economic event is imminent, whether opposite positions are permitted, and whether the trading server is accepting requests normally.
The architecture presented in this article is based on a simple principle:
A valid trading signal does not automatically imply permission to open a trade.
The execution engine should remain subordinate to an admission and protection layer.
As a practical example, we examine the architecture behind XAU RuleShield MT5, a Gold-oriented Expert Advisor for MetaTrader 5.
The system combines:
- directional market participation;
- a primary MASTER basket;
- a secondary MICRO recovery layer;
- volatility-aware price spacing;
- basket-level profit management;
- account-aware drawdown protection;
- an independent OCO engine for high-impact USD news;
- Strategy Tester logic for evaluating both monetary and time-based constraints.
The objective is not to present a guaranteed trading method, but to show how several execution and protection modules can be organized into one coherent EA architecture.
2. Overall EA Architecture
The Expert Advisor is organized as a sequence of decision layers rather than as one monolithic entry function.
A simplified execution path is:
ACCOUNT / ENVIRONMENT ↓ BROKER & SYMBOL VALIDATION ↓ ACCOUNT PROTECTION ↓ MARKET FILTERING ↓ DECISION ENGINE ↓ MASTER BASKET ↓ SECONDARY MICRO LAYER ↓ BASKET MANAGEMENT ↓ TP / TRAILING / PROTECTION EXIT ↓ RESET
A separate branch handles economic-news trading:
ECONOMIC CALENDAR ↓ HIGH-IMPACT USD EVENT ↓ NORMAL ENTRIES SUSPENDED ↓ OCO NEWS ENGINE
This separation is important.
The market engine determines what it would like to do.
The protection engine determines what it is allowed to do.
The execution layer acts only after both conditions agree.
A valid setup can therefore be rejected because of spread, account risk, margin, exposure, news, hedging restrictions, or server-request protection.
3. Primary MASTER Basket
Once a new trading cycle is authorized, the EA creates the primary directional structure: the MASTER basket.
Instead of opening the complete intended exposure as one market order, the volume can be divided into several slices.
The basic structure is:
MASTER #1 → MARKET MASTER #2 → LIMIT MASTER #3 → LIMIT MASTER #4 → LIMIT ...
For a BUY basket:
Current Market │ MASTER #1 BUY MARKET │ MASTER #2 BUY LIMIT │ MASTER #3 BUY LIMIT │ MASTER #4 BUY LIMIT ▼
For a SELL basket:
▲ MASTER #4 SELL LIMIT │ MASTER #3 SELL LIMIT │ MASTER #2 SELL LIMIT │ MASTER #1 SELL MARKET Current Market
MASTER #1 establishes immediate exposure.
The remaining MASTER slices are positioned farther into an adverse movement in the same direction.
Suppose the sizing engine determines an intended MASTER exposure of:
0.20 lots
A four-slice structure could conceptually use:
MASTER #1 = 0.05 MASTER #2 = 0.05 MASTER #3 = 0.05 MASTER #4 = 0.05
The exact distribution does not need to be equal.
The important principle is that exposure is deployed progressively rather than committed entirely at the first entry.

4. Shared Volatility-Aware Grid Distance
MASTER and MICRO positions use the same price-spacing engine.
The current implementation calculates the effective distance as:
GridDistance = max( GoldGridPoints × Point, ATR × GridATRMultiplier ) × GridDensityMultiplier × 3
The final × 3 is already applied inside the shared distance function.
It should therefore not be multiplied again by MASTER or MICRO callers.
This design avoids duplicated spacing logic and ensures that both layers use the same volatility-adjusted reference.
Why combine a fixed distance with ATR?
Gold volatility can change rapidly.
A fixed spacing that is reasonable during a quiet session can become dangerously narrow during a volatile session.
Using:
max(FixedDistance, ATRDistance)
provides two safeguards.
The fixed component prevents the grid from becoming too dense when volatility is very low.
The ATR component allows spacing to expand when volatility increases.
The density multiplier then provides an additional way to control how concentrated the basket becomes.
Because spacing changes the distribution of exposure, grid density should be treated as a risk parameter, not merely as a visual preference.
5. Secondary MICRO Recovery Layer
The second basket component is the MICRO layer.
It is not a new independent trading signal.
It is a same-direction recovery extension belonging to the existing MASTER cycle.
An important characteristic of the current implementation is:
the MICRO layer does not need to wait for the entire MASTER ladder to execute.
It can activate while one or more MASTER pending orders are still present.
The trigger is anchored to the original MASTER #1 price.
For a BUY basket:
MICRO Trigger = MASTER #1 Price - GridDistance
For a SELL basket:
MICRO Trigger = MASTER #1 Price + GridDistance
This fixed anchor is important.
If the trigger were recalculated from the latest MASTER fill, each new MASTER execution could move the MICRO trigger farther away.
Using MASTER #1 prevents that behavior.
A conceptual SELL structure is:
PRICE RISES ▲ MICRO #5 │ MICRO #4 │ MICRO #3 │ MICRO #2 │ MICRO #1 │ ─── MICRO TRIGGER ─── │ MASTER pending │ MASTER pending │ MASTER #1 ORIGINAL ANCHOR
When the trigger is reached and the protection layer allows more exposure, the recovery structure can be created.
The implementation uses up to five MICRO legs:
MICRO #1 → 0.01 lot MARKET MICRO #2 → 0.01 lot LIMIT MICRO #3 → 0.01 lot LIMIT MICRO #4 → 0.01 lot LIMIT MICRO #5 → 0.01 lot LIMIT
All MICRO legs use the same shared grid distance as the MASTER structure.
However, reaching the trigger does not guarantee execution.
Additional recovery exposure can still be blocked because of:
- excessive adverse volatility;
- insufficient drawdown room;
- basket exposure limits;
- broker volume constraints;
- insufficient margin;
- account rules;
- request-guard restrictions.
Therefore:
Trigger reached
means:
Recovery requested
not:
Recovery guaranteed
The system also prevents duplicate recovery ladders by checking whether a MICRO position or MICRO pending order already exists.
6. Basket Management and Atomic Trailing
Once several positions exist, managing them as unrelated tickets becomes inefficient and potentially misleading.
The architecture therefore reconstructs a managed basket state.
Typical basket information includes:
Position count BUY volume SELL volume MASTER positions MASTER pending orders MICRO positions MICRO pending orders Weighted average price Floating P/L Basket age Total exposure Trailing state Protection state
A particularly important design choice is that basket direction is based on actual volume exposure, not simply on ticket count.
Consider:
BUY: 4 × 0.01 = 0.04 lots SELL: 1 × 0.20 = 0.20 lots
Ticket counting gives:
4 BUY 1 SELL
but economically the basket is SELL-dominant.
Volume-based evaluation gives:
BUY exposure = 0.04 SELL exposure = 0.20 Net exposure = -0.16 lots
This is a more meaningful representation of risk.
The same basket-level philosophy is used for profit protection.
Instead of trailing each ticket independently, the EA applies an atomic basket trailing mechanism to the complete NON-OCO basket.
The trailing logic uses three concepts:
Activation Distance Step
Activation defines the basket profit required before trailing becomes active.
Distance defines the permitted giveback from the protected basket-profit peak.
Step defines the minimum additional improvement required before the peak is advanced.
The mechanism is also composition-aware.
Suppose trailing arms with:
3 positions 0.15 total lots
and later another MASTER order executes.
The basket may then become:
4 positions 0.20 total lots
The old profit peak was calculated on a different exposure structure.
For this reason, material basket-composition changes reset the trailing state.
Relevant changes can include:
Position count BUY/SELL composition Total lots MASTER pending count MICRO open count MICRO pending count
Another important distinction is:
MICRO recovery may activate while MASTER pending orders exist.
But:
basket trailing does not arm while MASTER or MICRO pending structures remain.
These rules serve different purposes.
MICRO controls recovery deployment.
Basket trailing protects profit only after the exposure structure has stabilized.
7. Account Protection, Drawdown and Safety Buffer
The account-protection layer adds another level of control.
External trading environments may impose restrictions such as:
Daily loss Total loss Trailing drawdown Profit target Minimum trading days Maximum calendar days Holding time Hedging restrictions News restrictions
A strategy can therefore be profitable and still violate account rules.
The purpose of the protection engine is not to predict Gold.
Its purpose is to determine whether additional exposure remains admissible.
A useful concept is remaining room: the monetary capacity available before an internal buffered protection threshold is reached.
This distinction is important because:
The account has not violated a rule
does not necessarily mean:
The account has enough safe room for another trade
Different drawdown models can also use different references.
Daily drawdown may be based on:
Start-of-day balance Start-of-day equity Intraday high-water mark
Total drawdown may instead use:
Initial balance High-water mark Trailing floor
Consider:
Initial reference = $100,000 Loss allowance = $5,000 Equity high = $103,000
If the loss floor follows the high-water mark:
$103,000 - $5,000 = $98,000
A later fall to $98,000 can therefore reach the modeled limit.
This illustrates why closed balance alone is not always enough to measure available risk.
Safety Buffer
The system can also apply a safety buffer inside an official external limit.
For example:
Reference balance $100,000
Official daily loss 5.0%
Official amount $5,000
Safety buffer 0.5% Under a simple percentage model, the internal protection threshold becomes approximately:
4.5% = $4,500
The remaining margin helps account for factors such as:
- spread expansion;
- commission;
- swaps;
- slippage;
- execution latency;
- differences between internal and external calculations.
The buffer does not modify the external rule.
It changes the point at which the EA starts restricting new risk.
Risk control can also be progressive rather than purely binary.
Instead of only:
ALLOW BLOCK
the protection layer can conceptually scale exposure:
Large remaining room → 100% Reduced room → 90% Lower room → 75% Critical room → 50% Insufficient room → 0%
This creates an important distinction between:
Desired volume
and:
Authorized volume
For example:
Strategy requests: 0.20 lots Protection allows: 0.10 lots
The signal remains valid while account protection reduces the allowed implementation.
8. OCO News Engine
High-impact USD economic releases can produce market conditions very different from normal trading.
The EA therefore contains a separate OCO — One Cancels the Other — news branch.
When a qualifying high-impact USD news day is active, normal RuleShield entries can be suspended.
The OCO engine then waits for the configured lead window before placing two opposing pending orders:
BUY STOP ▲ │ Current Market │ ▼ SELL STOP
Representative implementation parameters include:
OCO lot 0.10 Lead time 30 seconds Pending expiry 300 seconds Entry distance 2.00 USD Emergency SL 8.00 USD Trailing distance 1.50 USD Trailing step 0.30 USD
These are implementation defaults, not universal trading recommendations.
Suppose the news release produces an upward breakout.
The sequence becomes:
BUY STOP triggered ↓ BUY position opened ↓ SELL STOP deleted ↓ Independent OCO management
For a downward breakout:
SELL STOP triggered ↓ SELL position opened ↓ BUY STOP deleted ↓ Independent OCO management
The engine therefore does not need to predict the news direction before the release.
It prepares two conditional scenarios and retains only the side activated by the market.
The OCO branch uses a dedicated Magic Number.
This is essential because a news position should not be included in the normal MASTER/MICRO basket calculations.
Conceptually:
MAIN MAGIC ↓ MASTER + MICRO OCO MAGIC ↓ NEWS POSITION
This separation prevents OCO exposure from distorting:
Basket direction Weighted average prices Basket P/L Trailing state Recovery logic
9. Strategy Tester and Prop Evaluation Logic
A conventional backtest often focuses mainly on final profit.
An evaluation-style simulation may require more.
Suppose we test:
Starting balance $100,000 Profit target 10% Minimum trading days 4
The target equity is:
$110,000
If the EA reaches $110,000 on the second trading day, the monetary requirement has been achieved.
But if the modeled evaluation requires four trading days, the full condition is not yet complete.
The Strategy Tester therefore needs to distinguish between:
TARGET REACHED
and:
EVALUATION PASSED
A valid PASS can require both:
MONETARY REQUIREMENT + TIME REQUIREMENT
while remaining inside the applicable drawdown constraints.
Consider a simplified example:
Starting balance $100,000 Profit target 10% Daily loss limit 5% Total loss limit 10% Safety buffer 0.5% Minimum trading days 4
The target equity becomes:
100,000 × 1.10 = $110,000
Under the simplified buffer model:
Daily: 5.0% - 0.5% = 4.5% Total: 10.0% - 0.5% = 9.5%
If $110,000 is reached on day two:
Profit target: COMPLETE Trading days: 2 / 4 Time requirement: INCOMPLETE Final state: WAITING
After the fourth valid trading day:
Profit target: COMPLETE Trading days: 4 / 4 Time requirement: COMPLETE Final state: PASS
provided no applicable loss or calendar restriction has been violated.
This illustrates why an evaluation-oriented backtest should consider account rules rather than final profit alone.
10. Live Monitoring and Operational State
Once an EA contains multiple execution and protection systems, the Trade tab alone is not sufficient to explain what the program is doing.
The live interface can therefore expose separate information blocks.
Basket Monitor
Typical information includes:
Current P/L Position count BUY lots SELL lots MASTER open MASTER pending MICRO open/pending Basket trailing state
Account Protection
Typical information includes:
Daily drawdown Daily room Total drawdown Total room Profit target Remaining target Trading days Calendar days
OCO News
Typical information includes:
Engine state Normal-entry state OCO Magic Number OCO volume Next event T-minus Entry gap Emergency SL Trailing distance Trailing step Lead time Expiry
Separating these blocks makes it easier to distinguish market state, basket state, account protection and news execution.
Persistent state is also important.
Some information should survive terminal or EA restarts, for example:
Daily drawdown reference High-water mark Challenge start Trading-day state Request counters Protection locks
If an account is already close to a daily limit, restarting MetaTrader should not make the EA assume that full risk capacity is available again.
Persistence therefore becomes part of the risk architecture.
The same applies to server-request protection.
Complex EAs can generate many requests:
Market orders Pending orders Order deletions Stop modifications Position closures Retries
Repeated rejected requests should not create an uncontrolled resend loop.
A request guard can track activity and repeated failures, then back off or temporarily restrict operations.
However, protective code must itself be designed carefully.
A request lock that is too restrictive may also interfere with legitimate position management.
11. Limitations and Practical Considerations
Historical testing and live trading are not equivalent.
Economic-calendar logic is a particularly important example.
Live MetaTrader operation can use the current calendar feed.
Historical Strategy Tester operation cannot always reproduce the same events with identical fidelity.
Therefore, a backtest should not be expected to reproduce the live OCO News branch exactly.
Other differences include:
| Strategy Tester | Live Environment |
|---|---|
| Historical/generated ticks | Real-time broker prices |
| Simulated fills | Real execution |
| Tester spread assumptions | Dynamic live spread |
| Simulated broker responses | Real rejection and slippage |
| Limited historical calendar behavior | Current calendar feed |
| No real network latency | Network/server latency |
Broker differences also matter.
The same EA and parameters can behave differently because of:
Gold contract size Point size Tick size Tick value Minimum lot Volume step Spread Commission Swap Slippage Historical data Symbol suffix Margin requirements
This is especially important for XAUUSD because apparently small symbol differences can materially change monetary exposure.
No Expert Advisor can guarantee compliance with external trading-program rules.
Rules can change.
Calculation methods can differ.
Execution can diverge from historical results.
The EA cannot control:
- broker outages;
- network interruptions;
- price gaps;
- slippage;
- spread spikes;
- incorrect economic-calendar data;
- proprietary external account calculations.
Safety buffers reduce available trading room intentionally, but they cannot eliminate execution risk.
Embedded presets should therefore be treated as software configurations, not as authoritative statements of third-party rules.
Any selected rules should be checked against the actual account conditions before live use.
12. Conclusion
Building a complex Expert Advisor involves much more than deciding when to buy or sell.
The architecture examined in this article separates the trading process into several cooperating responsibilities.
The MASTER basket creates the primary directional exposure.
The MICRO layer provides a controlled same-direction recovery extension and can activate independently of MASTER-ladder completion while remaining anchored to the original MASTER #1 price.
The shared volatility-aware spacing engine keeps MASTER and MICRO distances consistent.
The basket manager evaluates actual directional volume rather than simply counting tickets.
The atomic basket trailing system protects the profit of a stable basket as one unit.
The account-protection layer determines whether additional risk remains admissible.
The OCO News Engine handles high-impact USD events through a separate execution branch and dedicated Magic Number.
The Strategy Tester layer evaluates not only monetary performance but also modeled drawdown and time requirements.
The broader lesson applies well beyond Gold trading:
A mature trading robot should not ask only whether a signal exists. It should also determine whether executing that signal is still acceptable under the current market, account and execution conditions.
That distinction is what transforms an entry algorithm into a complete trading system.






