MdevTrade: From Idea to a Complete AI Trading Agent
Table of Contents

I. It Started with a GitHub Repo #
It started on a free evening. I was browsing GitHub and forked the TradingAgents project on reflex.
Instead of dry if-else code scanning technical indicators, the project uses a completely different model: several AIs playing different roles. It simulates a miniature trading desk inside RAM. There is a news analyst, a camp convinced the price is going up and a camp convinced it is going down arguing at each other, and a manager who makes the call.
At that point I asked myself: can large language models (LLMs) actually synthesize macro news into a market prediction? Or is all that crisp-sounding reasoning just sophisticated bluffing produced by probability?
To find out, I copied the core idea and rewrote it into a version that was more experimental and safer. Whether the system performs well I honestly do not know, but I have already hit start. Run it for a while and see whether it burns the money or makes some.
To be able to sleep at night, I set hard risk limits:
- No margin, no leverage β no borrowing from the exchange to trade larger than my own capital. Borrowing magnifies gains and liquidates accounts just as fast.
- Spot only β buying means actually owning the asset, not holding a derivative contract. Beyond the basic trading fee there are essentially no hidden costs, so positions can be held for a long time without the account bleeding quietly.
- Even buying via DCA (dollar-cost averaging): split the money across many purchases instead of one large entry. Some buys land high, some land low, and the average cost comes out kinder than trying to call the bottom.
- One asset only: tokenized gold (XAUT/USDT) β a token where each unit is backed by physical gold.
I decided to share the whole customized version. What follows is what I did in the source code, and what the research turned up.
II. Feasibility Research and Customization #
Before touching code, I read through the academic material to see whether the idea holds up. The five conclusions below shaped every customization in the project.
1. News Has a Shelf Life, and It Is Shorter Than You Think #
My original idea was greedy: use AI to forecast trends 2 to 6 months out.
But research shows financial news has a very short half-life β a term borrowed from nuclear physics, meaning that after a certain interval half of the news’s effect has already dissipated from the price. For financial news, that interval is measured in days and weeks, not months.
Force the model to forecast far out and it is blind to shocks that have not happened yet. And rather than admitting “I do not know,” an LLM bluffs by extending today’s trend into next month along a straight line. That is a recipe for disaster.
- My customization: pull the forecast window back to 1 to 4 weeks. This is where an LLM synthesizes market sentiment best. At the execution layer I use a dynamic ATR band to take profit within these short moves. ATR (average true range) measures the average size of price swings over a period β loosely, “how much does this thing move on a normal day” β so anchoring exits to it flexes with the market instead of using a fixed number.
2. Do Not Make an LLM Do Arithmetic #
A lethal trap in AI work is dumping 200 days of price data into the prompt and hoping the model “sees” the 200-day moving average.
LLMs handle language extremely well and arithmetic over an array of numbers extremely badly β they do not really compute, they predict which number looks plausible. Stuffing in a pile of figures also dilutes attention, so the part that mattered gets skipped.
My customization: separate computation from reasoning completely.
In MdevTrade, the market analyst agent does not count candles. It calls standard Python libraries β
yfinanceandstockstatsβ to compute the indicators exactly: SMA (the average price over the last N days, used to read the overall trend) and MACD (comparing a short and a long average to catch the moment a trend turns). It then translates the result into sentences before feeding the prompt. For example: “Price sits above the 200-day SMA with a positive slope, uptrend intact.”The computer does the arithmetic, the LLM does the reading β each doing what it is good at. For raw prices, the LLM sees only the last 14 to 30 days, enough to feel the short-term rhythm.
3. Review by Cycle, Not by Trade #
How does the AI learn from what happened? Making it re-read yesterday’s losing $5 order inside an even-buying strategy is pointless and burns API budget. One small order in a DCA sequence carries almost no information β more noise than signal.
My customization: evaluate over a whole cycle.
The execution layer computes the average cost of the entire multi-day accumulation β total money spent divided by total quantity bought. When the trend reverses, the summary handed back to the AI looks like this: “May uptrend cycle closed. Average cost $2,650. Net return +1.8%.” At that level of summary there is finally a pattern to recognize.
4. Never Trust an AI’s Confidence Level #
Should the AI decide the size of each order ( $5 to $10) based on how “confident” it feels? The answer from the research: absolutely not.
LLMs fail completely at judging their own certainty. They are trained to sound decisive, so they report “99% confident” while fabricating. Let one size its own positions and eventually there will be a day it puts everything into exactly the wrong place.
- My customization: hold fixed-DCA discipline at the execution layer. Order size is fixed by ordinary arithmetic, never bent by the AI.
5. Let AIs Argue Past Two Rounds and They Start Nodding Along #
At first I assumed that putting several AIs in a room to argue would produce truth. In practice, research shows that past the second round they start agreeing with each other β models are trained to converge and keep a conversation pleasant, so one concedes by degrees, or both get stuck restating the same thing in different words.
- My customization: force the debate into exactly two rounds.
- Round 1 (blind): the two camps are isolated completely, each writing an independent report. Isolation prevents whoever writes second from anchoring on the first argument.
- Round 2 (cross-examination): each side may attack exactly one logical hole in the other’s case, with repetition of round one banned.
- Deadlock handling: when data is too noisy and neither side wins, the research manager may not split the difference. It must apply hard tie-breaker rules β narrowing the take-profit band because the market is risky, or deferring to the 200-day trend.
III. System Architecture: 5 Steps and 12 Agents #
After a while, the harsh truth surfaced: you never hand account authority to a system that runs on probability. An LLM, in the end, is a dice roller sitting on top of neural weights. The only way out is to contain that uncertainty inside the determinism of ordinary code.
Following the original author’s structure, I split the project into 5 steps with 12 agents, then reworked each node for my own operational stance.
The whole system splits into two completely independent halves. This is the most important point in the post: the AI half can never touch money.
1. AI Brain (Research Graph) #
Instead of writing one enormous prompt and praying, I use LangGraph to orchestrate the reasoning flow. LangGraph lets the process be described as a graph of steps: each node is one job, and the routing between nodes is hard code I wrote, not something the model decides. The model is free only inside a node.
Step 1 β Data gathering. Four agents in sequence:
Market Analyst: pulls price data with
yfinanceand computes technical indicators withstockstats.News Analyst: pulls macro financial news, filters noise, keeps only events capable of setting a 1-to-4-week trend.
Social Analyst: measures crowd sentiment β the fear and greed index, aggregated from price movement and discussion volume β from platforms like StockTwits, to read retail flow.
Fundamentals Analyst: scrapes an asset’s fundamentals (P/E, PEG, ROE) to judge whether it is cheap or expensive against intrinsic value.
[!NOTE] I coded this node to keep the original author’s architecture intact. In practice, applied to tokenized gold (XAUT), corporate financial ratios do not exist, so I skip this node.
Step 2 β Debate. Exactly two rounds, per Section II.5. Round one, both camps write independently from step 1’s data. Round two, they cross-examine, hunting logical holes or misread data. The research manager then condenses the sharpest arguments into a neutral report that acts as the compass for the decision stage.
Step 3 β Planning. From that report, the Trader agent proposes a concrete strategy: entry point, stop-loss level, take-profit level β all sized against real volatility rather than a qualitative “should buy” signal.
Step 4 β Risk management. The plan is scrutinized by three agents with three appetites: one pushing returns, one preserving capital, one checking compliance. On conflict or any sign of an abnormal all-in, the Portfolio Manager intervenes to resize or cancel outright.
Step 5 β Storage. The AI Brain is completely blindfolded to the real exchange balance. The Portfolio Manager’s final act is writing a static JSON file to the database containing exactly one decision β UP, DOWN, or STAY OUT β plus explanatory notes. That is all. No path leads from here directly to the exchange.
2. Execution Hands (Binance Graph) #
This is a conventional Python system holding the API keys and the authority. It reads the JSON from the AI Brain and decides whether to send an order.
Its heart is an automatic circuit breaker. However confident the AI is, if the portfolio falls more than 15% below its high-water mark, the breaker trips. All trading freezes immediately, and a human has to look before it runs again.
That mechanism is the crux: Software 1.0 using hard logic to keep Software 2.0 contained. The AI is allowed to be wrong β it certainly will be β but the magnitude of that wrongness is pinned by a number in code, not by whatever the model happened to think that day.
Honestly, I have not researched this execution layer deeply; everything sits at the most basic level required for safety. Some night when a fairy godmother shows up with a better design, I will rewrite this part.
IV. Conclusion #
Reading the daily reports this agent lineup produces, the logic holds up β sharp, credible. If I sat down with the charts and macro news myself, I doubt I would reach a very different conclusion.
But one thing has to be said plainly: “the report reads sensibly” and “the strategy is profitable” are two different claims, and the first does not prove the second. This is still a trial run. Markets always land unexpected hits, especially slippage β the executed price differing from the price you saw when placing the order, which happens when an asset has few buyers and sellers. Time will answer.
Whatever the P&L turns out to be, the project settled one thing: success in wiring AI into a product is not about throwing everything into a prompt-shaped black box and praying. It is about where you draw the line. The hard logic blocks β the flow graph, the circuit breaker, the data-fetching layer β are what contain and steer the probabilistic machine and force it to work with discipline. The AI half handles comprehension; the code half handles not losing money.
[!NOTE] The full source is public at: https://github.com/vinhmdev-com/mdevtrade
Special thanks to the author of the original TradingAgents project for the inspiration and the architectural ideas.