Designing a Gold Trading EA with Basket Management, Prop Firm Protection and an OCO News Engine

Designing a Gold Trading EA with Basket Management, Prop Firm Protection and an OCO News Engine

9 August 2026, 11:14
Augusto Nieddu
0
252

1. Introduction

An automated trading system is much more than an entry signal.

Before an Expert Advisor sends an order, it may need to verify spread, margin, current exposure, drawdown, trading restrictions, news events, account rules and server conditions.

The architecture presented here follows one fundamental principle:

A trading signal and permission to execute that signal are two different things.

The trading engine decides what it wants to do.

The protection layer decides whether the account is currently allowed to do it.

As a practical example, this article describes the architecture behind XAU RuleShield MT5, a Gold-oriented Expert Advisor designed for MetaTrader 5.

The system combines:

  • one shared trading engine for LIVE and PROP accounts;
  • directional basket execution;
  • volatility-aware entry spacing;
  • basket-level management;
  • account protection;
  • prop-firm evaluation rules;
  • an independent OCO news engine;
  • persistent state and execution safeguards;
  • real-time monitoring.

The objective is not to present a guaranteed trading method.

The objective is to show how trading logic, account rules and execution protection can be organized inside one coherent EA architecture.

2. Overall Architecture

The EA is divided into several logical layers.

The main trading path is:

Account / Environment → Broker & Symbol Validation → Account Protection → Market Filtering → Decision Engine → Shared LIVE/PROP Trading Engine → Basket Management → TP / Trailing / Protection Exit

A separate branch handles scheduled high-impact USD news through an independent OCO engine.



Figure 1 — Overall EA architecture.
LIVE and PROP accounts share the same trading engine. Account-specific rules are enforced by the protection layer rather than by maintaining separate trading strategies. The OCO News Engine operates as an independent execution branch.


LIVE and PROP accounts share the same trading engine. Account-specific restrictions are enforced by the protection layer. The OCO News Engine operates as an independent execution branch.

This separation is important because each component has a different responsibility.

The Decision Engine analyzes the market.

The trading engine converts an accepted signal into exposure.

The basket manager controls existing positions.

The protection layer decides whether new risk is still permitted.

The news engine handles a special event-driven execution mode.


3. One Trading Engine for LIVE and PROP

A central architectural decision is to avoid maintaining two different trading strategies simply because the account belongs to a different category.

In the current architecture, LIVE and PROP accounts use the same core trading engine.

The following logic remains common:

  • market analysis;
  • directional decision;
  • basket creation;
  • additional basket entries;
  • exposure calculation;
  • basket management;
  • profit protection;
  • trailing logic;
  • exit logic.

What changes is the account protection environment.

A LIVE account may have relatively few external restrictions.

A PROP account can add rules such as:

  • daily loss limits;
  • maximum total loss;
  • trailing drawdown;
  • profit target;
  • minimum trading days;
  • maximum evaluation duration;
  • holding-time restrictions;
  • hedging restrictions;
  • news restrictions.

The important distinction is therefore:

Trading logic is not the same thing as account rules.

A strategy should not become a different strategy merely because the account is proprietary.

Instead, the same engine can operate inside different protection envelopes.



Figure 2 — Unified LIVE/PROP execution model.
Both environments use the same market and basket engine. PROP accounts add an admission layer that can reduce, delay or block exposure when evaluation rules or protection thresholds require it.


Both account types use the same market and basket engine. PROP accounts add rule validation that can reduce, delay or block exposure when evaluation constraints require it.

This approach reduces duplicated logic and makes the EA easier to maintain.

If a correction is made to the trading engine, both environments benefit from the same correction.

It also becomes easier to compare LIVE and PROP behavior because the market logic itself is not silently diverging.


4. Directional Basket Execution

The EA manages directional exposure as a basket rather than treating every position as an isolated trade.

When a valid setup is accepted, the system can open the first position and later add further entries according to the basket rules.

For example, a BUY basket may contain:

  • BUY #1;
  • BUY #2;
  • BUY #3;
  • BUY #4.

Instead of evaluating only the number of positions, the basket manager tracks the complete exposure structure.

Useful basket information includes:

  • number of BUY positions;
  • number of SELL positions;
  • BUY volume;
  • SELL volume;
  • net exposure;
  • weighted average entry price;
  • total floating profit or loss;
  • basket age;
  • current management state.

This allows the EA to reason about the complete trading cycle instead of managing unrelated tickets.


5. Volatility-Aware Entry Spacing

Gold volatility changes significantly between sessions and market conditions.

A fixed price distance that is reasonable during a quiet market may become too small during a fast movement.

For this reason, basket spacing can combine:

a fixed minimum distance

and

a volatility-derived distance

Conceptually:

Effective Distance = max(Fixed Distance, Volatility Distance)

The exact implementation can vary, but the architectural purpose remains the same.

Entry spacing is a risk parameter because it determines how quickly additional exposure is accumulated.

A dense basket deploys volume rapidly.

A wider basket deploys exposure more gradually.

Therefore grid distance should not be viewed only as an entry parameter. It directly affects risk concentration.


6. Basket Direction Should Use Exposure

Counting tickets alone can produce a misleading representation of market exposure.

Consider this example:

BUY positions:

  • 0.01 lot
  • 0.01 lot
  • 0.01 lot
  • 0.01 lot

Total BUY exposure:

0.04 lots

SELL positions:

  • 0.20 lot

Total SELL exposure:

0.20 lots

Ticket count suggests:

4 BUY versus 1 SELL

but actual exposure is clearly SELL-dominant.

The net exposure is:

0.04 - 0.20 = -0.16 lots

Therefore basket direction should preferably be evaluated through volume and economic exposure, not only through the number of positions.



Figure 3 — Basket direction based on actual volume exposure.
Ticket count alone can be misleading. Net volume provides a more meaningful description of the account's effective directional exposure.


7. Basket Management

Once several positions belong to the same trading cycle, independent ticket management may produce inconsistent results.

The basket manager therefore evaluates the complete active structure.

Typical calculations include:

  • weighted average entry price;
  • total BUY volume;
  • total SELL volume;
  • total floating P/L;
  • net directional exposure;
  • number of active positions;
  • basket age;
  • profit-protection state.

The trading cycle can be represented as:

Signal → First Entry → Additional Entries → Basket Management → Profit Protection / Exit → Reset

The objective is to manage exposure as one coordinated structure.

This also makes it possible to apply basket-level Take Profit or adaptive trailing logic instead of making every position behave as an unrelated trade.


8. Account Protection Layer

The account-protection engine is independent from market prediction.

Its purpose is not to decide whether Gold should rise or fall.

Its purpose is to determine whether the account is still allowed to accept additional risk.

Depending on configuration, the protection layer can monitor:

  • current equity;
  • starting balance;
  • daily P/L;
  • total drawdown;
  • trailing drawdown;
  • available margin;
  • profit target;
  • minimum trading days;
  • maximum calendar days;
  • maximum holding time;
  • hedging restrictions;
  • news restrictions.

A market signal can therefore be valid while execution is blocked.

The logical flow is:

Valid Signal → Account Check → PASS or BLOCK

Only a PASS allows the order to reach the execution engine.

This distinction is fundamental because a strategy can be profitable while still violating account rules.


9. Safety Buffer and Remaining Risk Capacity

An account may still be technically inside an external drawdown limit while already being too close to that limit to justify opening additional positions.

For this reason, the EA can use an internal safety buffer.

Suppose a prop account starts at:

$100,000

and the external daily loss allowance is:

5%

The theoretical daily allowance is:

$5,000

However, the EA may stop or reduce new exposure before the entire $5,000 is consumed.

This creates protection against execution effects such as:

  • spread expansion;
  • slippage;
  • commissions;
  • swaps;
  • gaps;
  • price jumps;
  • execution delay.

The important question is therefore not only:

Has the account already violated the rule?

but also:

How much safe risk capacity remains?

This allows progressive control.

For example:

  • large remaining capacity → normal exposure;
  • reduced capacity → reduced exposure;
  • low capacity → strong reduction;
  • critical capacity → no new entries.

Thus the desired trading volume and the authorized trading volume do not necessarily need to be identical.




Figure 4 — Independent OCO News Engine.
During configured high-impact USD events, normal entries can be suspended while opposing conditional orders prepare for either breakout direction. Activation of one side cancels the other.


10. PROP Evaluation Logic

Prop-firm accounts can impose both monetary and time-based requirements.

A normal backtest often focuses on:

  • Net Profit;
  • Drawdown;
  • Profit Factor;
  • number of trades;
  • expected payoff.

A prop-style evaluation may additionally require:

  • a profit target;
  • minimum trading days;
  • maximum calendar duration;
  • daily loss compliance;
  • maximum loss compliance;
  • holding-time rules;
  • hedging rules;
  • news restrictions.

For example:

Starting balance:

$100,000

Profit target:

10%

Target equity:

$110,000

Suppose the EA reaches $110,000 after only two valid trading days while the account requires four minimum trading days.

The monetary objective has been achieved, but the evaluation has not yet been completed.

The system therefore distinguishes between:

TARGET REACHED

and

EVALUATION PASSED

A complete PASS may require all relevant conditions to be satisfied.

Figure 5 — PROP Evaluation State

[INSERT FIGURE 5 HERE]

Figure 5 — PROP evaluation state.
Reaching the monetary profit target and completing the evaluation are separate states. A PASS is obtained only when the required profit, timing conditions and protection rules are all satisfied.

This is also why the Strategy Tester monitor distinguishes between values such as:

  • Trading Days;
  • Calendar Days;
  • Profit Target;
  • Daily Loss;
  • Maximum Loss;
  • Evaluation Status.

Trading Days and Calendar Days represent different concepts.

A calendar day is simply elapsed time.

A trading day is a day that qualifies as trading activity according to the EA's evaluation logic.


11. Independent OCO News Engine

High-impact economic releases can produce market behavior that is very different from normal conditions.

For this reason, the EA includes an independent OCO — One Cancels the Other — news engine.

The OCO branch is separated from the normal trading engine.

When a qualifying high-impact USD event approaches, the EA can temporarily suspend normal entries.

The news engine can then prepare two opposing conditional orders:

BUY STOP above the current market

and

SELL STOP below the current market

If the upward breakout activates the BUY STOP:

  • the BUY position becomes active;
  • the opposite SELL STOP is cancelled;
  • the OCO position enters its own management logic.

If the downward breakout activates the SELL STOP:

  • the SELL position becomes active;
  • the opposite BUY STOP is cancelled;
  • the OCO position enters its own management logic.

The purpose is not to predict the direction of the news.

The engine prepares two conditional scenarios and allows the market to select the active side.


Figure 5 — PROP evaluation state.
Reaching the monetary target and completing an evaluation are separate states when minimum trading-day or other time requirements apply.


During configured high-impact USD events, normal entries can be suspended while opposing conditional orders prepare for either breakout direction. Activation of one side cancels the other.

The OCO module can use its own Magic Number so that news positions remain logically separated from the normal basket.

Typical OCO parameters can include:

  • lot size;
  • entry gap;
  • emergency Stop Loss;
  • trailing distance;
  • trailing step;
  • event lead time;
  • pending-order expiry.

This separation helps prevent normal basket logic and event-driven logic from interfering with each other.


12. Live Monitoring

As an EA becomes more complex, the standard MetaTrader Trade tab is often not enough to explain its internal state.

The runtime monitor can therefore display several groups of information.

Account Information

Typical values include:

  • account type;
  • starting balance;
  • current equity;
  • net result;
  • EA status.

Protection Information

The monitor may show:

  • Daily Loss Limit;
  • Maximum Loss Limit;
  • Total Drawdown Mode;
  • Profit Target;
  • Trading Days;
  • Calendar Days;
  • protection state.

Trading Engine Information

Typical values include:

  • market bias;
  • active basket;
  • BUY exposure;
  • SELL exposure;
  • floating result;
  • normal-entry status.

OCO Information

The OCO section can show:

  • OCO engine ON/OFF;
  • current state;
  • next high-impact USD event;
  • T-minus countdown;
  • OCO lot;
  • entry gap;
  • emergency Stop Loss;
  • trailing distance;
  • trailing step;
  • lead time;
  • pending expiry;
  • normal entries ACTIVE or SUSPENDED.

The purpose of the monitor is not decorative.

It provides a real-time explanation of what the system believes is happening.


13. Persistence

Some protection variables should survive terminal restarts.

Examples include:

  • daily reference balance;
  • account high-water marks;
  • evaluation starting state;
  • trading-day counters;
  • protection locks;
  • request counters.

Without persistence, restarting MetaTrader could reset information that logically belongs to the account rather than to the current EA session.

For this reason, important state can be stored using MT5-native persistent mechanisms such as terminal Global Variables or equivalent persistent storage.

The goal is continuity.

If the EA is restarted, it should not behave as if the account itself had also been reset.


14. Execution Protection

A complex EA can generate many trading requests:

  • market orders;
  • pending orders;
  • stop modification;
  • pending cancellation;
  • position closure;
  • retries.

Repeated failures should not create uncontrolled resend loops.

A request guard can therefore monitor trading-server interactions and temporarily restrict new activity when abnormal behavior is detected.

Possible events include:

  • repeated rejected orders;
  • repeated modification failures;
  • excessive request frequency;
  • temporary trade-server errors.

However, execution protection must not become more dangerous than the problem it is designed to solve.

Critical safety actions should remain able to operate.

For example, emergency closures or account-protection actions should not be prevented merely because normal requests are temporarily limited.


15. Strategy Tester vs Live Environment

Historical testing and live trading are not identical.

The Strategy Tester can reproduce the algorithmic logic, but several environmental characteristics differ from real execution.

Strategy Tester

  • historical or generated ticks;
  • simulated execution;
  • modelled spreads;
  • no real network latency;
  • simplified server behavior;
  • limited reconstruction of some external conditions.

Live Trading

  • real-time broker prices;
  • dynamic spreads;
  • real slippage;
  • actual server rejection;
  • real latency;
  • changing liquidity;
  • current economic calendar conditions.

Broker specifications can also affect Gold trading significantly.

Important symbol characteristics include:

  • contract size;
  • point size;
  • tick size;
  • tick value;
  • minimum lot;
  • lot step;
  • spread;
  • commission;
  • swap;
  • margin requirement;
  • symbol suffix.

This means that the same strategy parameters should not automatically be assumed to produce identical monetary behavior on every XAUUSD symbol or broker.


16. Why the Unified Architecture Matters

The most important architectural improvement is not another indicator.

It is the removal of unnecessary differences between account environments.

A complex EA can easily evolve into:

LIVE Engine + PROP Engine + Special Cases + Duplicated Management

Over time this creates several problems:

  • fixes applied to one engine but not the other;
  • different behavior between testing and live deployment;
  • duplicated functions;
  • unused inputs;
  • harder debugging;
  • increased maintenance risk.

A cleaner structure is:

ONE TRADING ENGINE

with:

LIVE → standard environment

and

PROP → same trading engine + additional protection rules

This architecture has several advantages.

The same strategy can be evaluated across account types.

Behavior becomes easier to compare.

Trading logic does not silently diverge.

Bug fixes affect both environments.

Account restrictions remain where they logically belong: inside the protection layer.


17. Separation of Responsibilities

A useful way to understand the complete EA is to assign one responsibility to each layer.

Decision Engine

Analyzes the market and determines the preferred direction.

Shared Trading Engine

Creates and extends the directional basket.

Basket Manager

Calculates exposure, average price, floating result and profit-protection state.

Account Protection

Determines whether additional risk is permitted.

PROP Evaluation

Tracks account-specific monetary and time requirements.

OCO News Engine

Handles high-impact USD events using an independent execution branch.

Persistence

Preserves important account state across terminal restarts.

Request Protection

Prevents uncontrolled server-request loops while preserving critical safety actions.

This separation reduces unintended interactions between components.


18. Conclusion

Building a production-oriented Expert Advisor involves much more than deciding when to buy or sell.

A reliable system must manage market analysis, exposure, execution, account rules and operational state at the same time.

The architecture presented here separates those responsibilities.

The Decision Engine evaluates the market.

The Shared Trading Engine executes the same core strategy for LIVE and PROP accounts.

The Basket Manager treats multiple positions as a coordinated exposure structure.

The Account Protection Layer determines whether additional risk remains acceptable.

The PROP Evaluation Layer tracks monetary and time-based requirements without creating a second trading strategy.

The OCO News Engine handles high-impact USD events through a separate execution path.

The Persistence and Request Protection Layers preserve operational state and protect communication with the trading server.

The broader principle is simple:

A mature trading system should separate market decisions from permission to take risk.

And a second principle follows naturally:

Different account rules do not necessarily require different trading strategies.

A single well-defined trading engine surrounded by environment-specific protection is easier to test, maintain and understand than several increasingly divergent implementations.

That separation is what turns an entry algorithm into a complete trading system.