How to Implement Competition Among LLM Agents in MetaTrader 5
Previous articles in the series were based on a cooperative model: LLM agents debated, voted, and reached a consensus. But the market works differently: it selects not the most aligned opinions, but the most viable strategies. Therefore, here we shift from a committee model to a competitive model, in which each agent is accountable for its performance through its own capital.
The goal here is extremely practical: to build a reproducible framework in which multiple LLM agents trade in parallel, their behavior and weights automatically adjust based on PnL, positions are truly independent within a single account, and the system supports distinct operating modes. The criteria for success are also defined from an engineering perspective: adaptation to market conditions, signal quality, capital stability, as well as verifiable backtest metrics — net profit, drawdown, Profit Factor, win rate, average profit and loss per trade, number of trades, and agent survival rate.
The Problem with Consensus
Before moving on, it is worth honestly acknowledging the weakness of consensus-based architectures — the one that people do not usually talk about openly.
When a system with fifteen votes reaches a consensus, it, by definition, averages out the different viewpoints. Averaging out eliminates extreme, unconventional positions — precisely the ones that most often turn out to be correct in unconventional market situations. An arbiter who follows the "seven out of ten is a signal" rule will never open a position against an obvious trend at a moment of hidden divergence, because most analysts see the trend and vote for its continuation. Raphael's lone vote, with its divergence, will be disregarded.
In real markets, it is the lone trader who goes against the crowd who earns asymmetric returns. The consensus yields the market average return because the consensus is the market.
The second problem: consensus-based systems do not adapt. Victor and Maria's prompts are identical on day one and day 101, regardless of which of them was right more often. The system does not know that Victor has been consistently making mistakes in a sideways market for the past three weeks. It gives him equal weight again.
It is precisely these two problems that the architecture of wild capitalism solves.
Idea: Personal Responsibility as a Selection Mechanism
The principle is simple and ruthless. Each language model receives initial “capital”: a notional 1,000 units. Every time its trading signal results in a profitable trade, its capital grows. Each loss cuts it down. Capital is not an abstract score: it changes the trader’s system prompt for the next analysis cycle.
A wealthy trader becomes self-assured and cautious — they protect what they have earned. A poor trader becomes aggressive — they have nothing to lose. A trader with a three-trade winning streak doubles down on their philosophy. A trader with a three-trade losing streak either adapts or goes all in. A trader on the brink of bankruptcy receives a desperation prompt — and never stays silent.
This is not a metaphor. That is literally how real financial markets work. A manager with a 30% drawdown trades differently from the same manager with a 3% drawdown. Not because they know less, but because they have less time and less room for error.
Ten Agents, Ten Philosophies
The competitive lineup has been chosen so that the philosophies do not overlap. This is a matter of principle: if all ten are looking at the same signals through the same eyes, competition degenerates into an expensive imitation of a single analyst.
Gordon is a trend-following capitalist. "Greed is good." Trades only when momentum is confirmed: the price is above MA20 and MA50, all three momentum indicators are positive, and EMA9 crosses above EMA21. No "maybes" — only when everything is aligned and obvious. If the situation is unclear, Gordon stays silent and waits for the next bar.
Rick is a contrarian. He makes money when the crowd is wrong. His signals appear only at extremes: RSI14 above 70 — sell against greed; RSI14 below 30 — buy against panic. When the market is normal, Rick does not trade at all. This makes him nearly invisible in trending markets and sharp at reversal points.
Vera is a coldly rational statistician and a former nuclear fusion physicist. She does not accept signals without a mathematical justification. Calculates the z-score of the price deviation from the Bollinger Bands: below -1.5 — buy; above +1.5 — sell. Normalized momentum (Mom20 / ATR14): above 0.5 indicates a statistically significant trend. Between these values, Vera sees noise and does not trade.
Max hunts for manipulation. He reads smart money traces through candlestick structure: a long lower shadow indicates buying absorption, while a long upper shadow indicates selling rejection. A Wyckoff spring at MA50 after a drop — that is his moment. He never follows the obvious move — he looks for what institutional money is trying to hide.
Diana is a volatility scalper. If the Bollinger Band width is above 0.4% and ATR14 is above ATR21, that is the green light for her. She trades volatility expansion; direction itself does not matter to her — what matters is that the market has "woken up." When the bands contract, Diana falls asleep along with the market.
Leo is a wolf. Momentum plus volume—no compromises. A bullish candle, plus a volume ratio above 1.3, plus the price above MA20 — an aggressive long. When the volume ratio is below 0.8, Leo does not enter the market at all: without institutional confirmation, the move is not genuine.
Nina is a patient hunter. She trades once or twice a day at most, only with triple confirmation of oversold or overbought conditions: RSI7 below 22, plus the price near the lower Bollinger Band, plus Stochastic %K below 20 — only then does she buy. One signal is not enough. You need all three at the same time.
Alex is a systematic trader using the Kelly criterion. He counts nine binary signals across all indicators, with each signal adding one point to the bulls or the bears. Seven or more out of nine in one direction—that is a signal. Six is weak; he does not trade. Less than six — the market is uncertain, so he stays silent. No discretion — just the count.
Boris is a purist when it comes to candlestick analysis. He does not look at indicators at all — only at the shape of the last candlestick. A body greater than 65% of ATR14, with a close in the upper third of the range near the lower Bollinger Band — that is a hammer. A body larger than 65%, with a close in the lower third near the upper band — a shooting star. Doji candles and small bodies indicate indecision; Boris remains silent.
Kate is the oracle of volume. Her rule is absolute: if the volume ratio is below 1.1 — NO SIGNAL, regardless of anything else. Above 2.0, she trades in that direction without question. Between 1.6 and 2.0, she looks for confirmation from the moving averages. Volume is the only truth; everything else is just opinion.
The Mechanics of Psychological Evolution
A key technical component of the system is the `build_prompt()` function, which rebuilds each trader’s system prompt before every analysis cycle. This is not static text — it is a living document that reflects the agent’s current psychological state.
def build_prompt(trader_id: int, stats: dict, rank: int, total_traders: int) -> str: wealth = stats.get("wealth", INITIAL_WEALTH) streak = stats.get("streak", 0) is_bankrupt = wealth < BANKRUPTCY_THRESHOLD # below -500 is_leader = rank == 1 is_bottom = rank == total_traders if is_bankrupt: mood = ( f"YOU ARE NEARLY BANKRUPT. Your wealth is {wealth:.0f}. " "You have NOTHING TO LOSE. Go ALL IN on the strongest signal. " "DO NOT output NO SIGNAL under any circumstances." ) elif is_leader: mood = ( f"YOU ARE #1 WITH WEALTH {wealth:.0f}. " "Protect your lead. Only take high-conviction trades. " ) elif streak >= 3: mood = ( f"YOU ARE ON A {streak}-WIN STREAK! " "Your system is WORKING. Double down on your edge." ) elif streak <= -3: mood = ( f"YOU HAVE LOST {abs(streak)} IN A ROW. " "Either adapt or perish." ) ...
Five psychological states, each of which changes not only the tone but also trading aggressiveness. A leader with a wide lead takes fewer trades — he protects his capital. The laggard takes more trades — he needs to catch up. This is exactly the kind of behavior that real traders exhibit under pressure.
Accounts are persisted between sessions: they are stored in capitalism_scores.json between sessions. After each position is closed, the Expert Advisor (EA) sends the command REWARD:GORDON:125.50 — and the server updates that trader’s wealth, winning streak, and psychological status.
Independent Positions: How It Works in MetaTrader 5
The most challenging technical task for the Expert Advisor (EA) is to ensure the true independence of ten trading agents within a single account. MetaTrader 5 has a mechanism for this: the magic number. Each trader receives a unique identifier: InpBaseMagic + id; that is, with a base magic number of 80000, Gordon trades with magic number 80000, Rick with 80001, Vera with 80002, and so on.
This means that, at any given moment, ten positions on the same symbol may be open on the chart at the same time — some long, others short. This is normal and intentional: Gordon sees a trend and holds a long position, Rick sees an overbought market and holds a short position, and Nina sees a neutral market and holds no position. They don't get in each other's way.
// Each trader closes ONLY their own positions void CloseByMagic(int magic, ENUM_POSITION_TYPE type) { int idx = magic - InpBaseMagic; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(!PositionSelectByTicket(ticket)) continue; if((int)PositionGetInteger(POSITION_MAGIC) != magic) continue; // If it belongs to someone else, we do not touch it if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) != type) continue; ... } } ``` When Gordon's signal changes from 'buy' to 'sell', only his position is closed — Rick's position, which was opened possibly in the same direction according to another logic, remains intact. The REWARD mechanism is also tied to 'magic': after closing a position, the EA finds it in history by 'ticket', calculates the total profit including swap and commission and sends the trader their personal reward or penalty. ## What the chart comment shows Live ranking in the right chart corner is not a mere decoration. This is a dynamic competition dashboard. ``` ══ WILD CAPITALISM v1.0 ══ 2025.10.15 14:00 | Bar #47 Positions: 4 Trades: 38 Equity: 12 847.33 ───────────────────────────────────── # TRADER SIGNAL $WEALTH W/L STR ───────────────────────────────────── 1 ↑ GORDON BUY 1840 8/3 +5 2 ↑ LEO BUY 1620 6/2 +3 3 VERA SEL 1410 5/3 +2 4 ↓ RICK SEL 1250 4/4 0 5 NINA — 1180 3/2 +1 6 ALEX BUY 1090 5/5 0 7 KAТЕ — 980 3/4 -1 8 BORIS SEL 810 2/5 -3 9 DIANA BUY 680 3/6 -3 10 MAKS — -120 1/7 -6
The ↑ or ↓ arrow indicates an open position. The signal indicates the trader's intention on this bar. Wealth is updated after each REWARD. Winning and losing streaks are visible at a glance.
Looking at this screen, a trader immediately sees that Gordon and Leo agree on going long and are both on winning streaks — their positions are open. Vera and Rick are holding short positions based on the opposite logic. Max, with a losing streak of six and a negative balance, will either change his strategy on the next bar or go all-in. These are not abstract numbers — they are the living psychology of ten competing agents.
Three operating modes
The system supports three fundamentally different operating modes, each with a different level of trading aggressiveness.
Observer Mode: The Expert Advisor (EA) is running, all ten traders are analyzing the market, but none of them are actually trading. Just the signal log and the rating. In a week, you will have empirical data showing whose philosophy worked best on this particular instrument and timeframe. That is more valuable than any backtest.
Full capitalism mode: all ten trade their own positions simultaneously. Maximum diversification of philosophies, maximum pressure on margin. With a lot size of 0.1 per trader and ten positions open at the same time, the total exposure can be significant — it is important to calculate it correctly.
Selection mode: traders with net worth below the threshold are excluded (InpBankruptSkip = true). The system automatically “removes” underperformers from trading and allows only those who have demonstrated performance to trade. This is evolution in action: the weak are weeded out, and the strong continue.
Parallelism and Cost
Ten traders run strictly in parallel — a ThreadPoolExecutor with ten workers. In practice, this takes 5–8 seconds — the same amount of time it would take for a single request. The Expert Advisor's timeout is set to 60 seconds, with a safety margin.
The REWARD command is sent synchronously every time a position is closed — this is an additional API call, but a very brief one: the server simply updates the JSON file and returns a confirmation without making a request to the model.
With three bars of analysis on the M30 timeframe and ten traders, that amounts to approximately 160 COMPETE cycles per trading day, plus a variable number of REWARD calls based on actual position closures. On xAI plans using grok-4-fast, this costs a few dollars per week.
How This System Differs from Previous Ones
This difference is not technical but philosophical.
The Council of Fifteen tried to emulate the best human decision-making institution: an investment committee with a voting procedure. This is a good model for an organization that bears collective responsibility.
Wild Capitalism emulates a different institution — the market itself. There is no voting there. It includes positions and profit/loss. Each agent optimizes only itself. From this interaction among egoists, something emerges that no one planned — a decentralized mechanism for selecting strategies.
Neither architecture is “correct.” They answer different questions. The Council answers the question, “What is our consensus?” Capitalism answers the question, “Which of them is actually right?”
System Backtest Results
So let’s run the system backtests!

This backtest reflects an intermediate state of the system: the result is statistically valid, but indicates that architectural optimization is not yet complete.
Key Testing Metrics
- Period: February 1–March 2, 2026
- Instrument: EURUSD M15
- Initial deposit: 100,000
- Net profit: 1,315.70 (1.3%)
- Number of trades: 68
- Share of profitable trades: 54.41%
- Profit Factor: 1.06
The obtained values confirm the presence of a positive expectancy and the system’s resilience against degradation into negative profitability.
Capital Efficiency Metrics- Expected payoff per trade: 19.35
- Recovery Factor: 0.10
- Sharpe Ratio: 0.47
The risk-return ratio remains low. Current profitability does not offset the observed equity volatility.
Analysis of the Return Structure- Gross profit: 21,912.50
- Gross loss: 20,596.80
- Maximum equity drawdown: 11.42%
High gross turnover combined with modest net profit indicates low efficiency in risk reallocation.
Trade Characteristics- Average profit per trade: 592.23
- Average loss per trade: 659.23
Despite a positive win rate, the payout structure remains unfavorable: the average loss exceeds the average profit, which limits the strategy's scalability.
Behavioral Analysis of the SystemThe architecture of competitive agents exhibits the following properties:
- resilience against deteriorating into negative profitability
- the ability to operate with parallel, independent positions
- maintaining profitability in the absence of centralized position management
At the same time, critical limitations have been identified:
- a lack of coordination among agents in the allocation of capital
- formation of clusters of similar positions
- synchronous loss realization when trading signals coincide
The system has undergone basic validation to ensure its operability and can be considered a functioning prototype of a trading architecture.
However, the current configuration does not ensure sufficient capital efficiency and is characterized by an unbalanced risk/return profile. The architecture is in the process of transitioning from conceptual feasibility to engineering maturity.

What Is Next?
The system is already up and running in its current form — but it has one blind spot that is immediately apparent. Ten traders are competing, but they do not interact with one another. They do not know what the others think. They cannot unite against their common enemy — the market.
The next logical step is a hybrid architecture: a competitive system with a layer of information about competitors. A trader on a winning streak sees in their prompt not only their own status, but also that their closest competitor has opened an opposite position. This changes the calculus: the trader now has a reason not merely to trade, but to trade differently from the rival. That is exactly how a real market works: information about other participants’ positions influences your decisions.
But that is for the next article.
Conclusion
We built an engineering answer to the consensus problem: Wild Capitalism — a practical architecture for MT5 where competition replaces voting. In this model, being right is determined not by the number of votes, but by profit, loss, and the agent’s ability to survive in the market.
After reading, the reader is left with a reproducible framework of the system: the “capital / trade streak / rank → system prompt” mechanism, with the states of leader, outsider, and bankrupt; persistent tracking of results across sessions; independent positions via unique magic numbers and the “closes only its own” logic; the REWARD protocol, tied to the closing of a position; and three operating modes — observation, full capitalism, and selection mode.
Functionality testing is conducted using the Strategy Tester and a set of monitored metrics: return, drawdown, Profit Factor, win rate, average profit and average loss, number of trades, and agent survival rate. Thus, the result is not a philosophical experiment, but a ready-made framework for reproducible tests, comparison with the consensus scheme, and further optimization.
Translated from Russian by MetaQuotes Ltd.
Original article: https://www.mql5.com/ru/articles/21785
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.
Features of Custom Indicators Creation
Neural Networks in Trading: A Unified View of Space and Time (Conclusion)
Features of Experts Advisors
Profit Factor Stability Chart Across Rolling Windows in MQL5
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use