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

I. A Project on GitHub and One Question #
A build log of an AI system I made to analyze and trade tokenized gold, modeled on an open-source project. It covers which jobs go to the AI, which must stay in plain code, and why that boundary decides whether the account survives.
A team of AIs reads the news, argues, then decides whether to buy or sell. I ran into that idea one free evening on GitHub, where programmers share source code. The project is TradingAgents, at https://github.com/TauricResearch/TradingAgents, and I forked it on reflex. Forking means copying a whole project into your own account to change freely.
Ordinary automated trading software follows prewritten rules like “buy if the price crosses this mark.” TradingAgents instead builds a miniature trading desk inside the computer, with an AI in each seat. There is a news reader, a camp arguing the price will rise, one arguing it will fall, and a manager who makes the call.
Each seat is an LLM, or large language model, the kind of AI behind ChatGPT: text in, text out. An LLM given its own role, task and tools is called an agent.
My question at the time: can LLMs really turn economic news into a market prediction? Or is all that crisp reasoning just words strung together by probability to sound plausible?
To find out, I kept the project’s core idea and rewrote it as a safer experiment. I honestly do not know yet whether it works, but I have already hit start. Let it run a while and see whether it burns the money or makes some.
To sleep at night, I set four hard risk limits:
No margin, no leverage. Margin is borrowing from the exchange to buy more than you own; leverage is the multiplier, say 5 times your capital. Gains and losses both multiply.
When losses eat nearly all your own money, the exchange sells to recover its loan: you get liquidated.
Spot only. Spot means buying outright: you pay and the asset lands in your wallet, like carrying gold home from the shop. Spot costs only a fee per trade, so holding it for a long time costs nothing extra. Borrowed trades and derivatives, contracts that track a price without you owning the asset, can keep charging for as long as you hold.
Even buying via DCA. DCA, short for dollar-cost averaging, splits the money into many regular purchases instead of one. Think of someone who buys a little gold every payday instead of guessing the cheapest day.
Some buys land high and some low, so the average cost ends up in the middle. Average cost is total money spent divided by total quantity bought. It is worse than buying the exact bottom, but it needs no guessing and avoids going all in at the peak.
One asset only: tokenized gold, the XAUT/USDT pair. A token is a unit of digital asset traded on a crypto exchange; each XAUT is backed by physical gold. USDT is a digital coin designed to stay worth one US dollar, so the pair prices XAUT in dollars.
The whole customized version is public. Below is what I read before coding, and how I built the system from it.
II. Five Things I Read Before Writing Code #
Before touching code, I read the research to see whether the idea held up. Five conclusions drove almost every change I made to the original.
1. News Moves Prices for Days to Weeks, Not Months #
My first idea was greedy: have AI forecast trends 2 to 6 months out.
But research shows financial news has a very short half-life. The term comes from nuclear physics: after that interval, half of the news’s effect has faded from the price. For financial news, that is days and weeks, not months.
News breaks, traders react, the price moves; once everyone has reacted, the news has no push left. Like a viral post: everyone discusses it on day one, nobody a week later.
Forecast too far and the model cannot see shocks that have not happened yet. LLMs also rarely say “I do not know”; they tend to stretch today’s trend into next month like a straight line. Betting money on that line is a recipe for disaster.
My customization: shrink the forecast window to 1 to 4 weeks, where an LLM reads market sentiment best.
The execution layer, the code that places orders directly (see Section III), takes profit using ATR. Taking profit means automatically selling at a preset price to lock in the gain.
ATR, short for average true range, measures how far the price swings on a normal day, averaged over recent days. Tied to ATR, the take-profit point widens when the market moves hard and tightens when it is calm, instead of staying fixed.
2. Do Not Make an LLM Do Arithmetic #
A common trap is to dump 200 days of prices into the prompt and hope the model “sees” the 200-day moving average. A prompt is all the instructions and data sent to an LLM in one request.
LLMs are good with language but unreliable at arithmetic over long lists of numbers: they do not actually add things up, they guess which number looks plausible. A pile of figures also makes them likelier to skip the part that matters. The result can be a very coherent analysis built on a miscalculated average.
My customization: fully separate computing from reasoning.
In MdevTrade, the market analyst agent does no math itself. It calls two Python libraries, meaning ready-made code to reuse: yfinance fetches prices, and stockstats computes technical indicators. Technical indicators are numbers derived from price history to read the trend.
SMA is the average price over the last N days; SMA 200 averages 200 days and shows the long trend. MACD compares a short average with a long one to catch a trend turning.
The agent then turns the numbers into sentences for the prompt, for example: “Price is above the SMA 200, which is sloping up: the uptrend holds.”
The computer does the math, the LLM does the reading, each doing what it is good at. Of the raw prices, the LLM sees only the last 14 to 30 days, enough to feel the short-term rhythm.
3. Learn From Whole Cycles, Not Single Orders #
How does the AI learn from experience? The model is not retrained; old summaries are simply added to the prompt in later runs.
The obvious approach is to have it re-read every order. But in a DCA strategy, yesterday’s losing $5 order says almost nothing: more noise than signal. Reviewing each one also burns API money, since every LLM call is billed by the amount of text sent and received.
Like the payday gold buyer: one purchase on a high-price day looks like a loss, but what matters is the average cost of the whole run.
My customization: evaluate by cycle, meaning a whole run of buying tied to one price trend.
The execution layer computes the average cost of the whole cycle, which usually spans many days. When the trend reverses, it sends the AI a summary like this (illustrative numbers): “May uptrend cycle closed. Average cost $2,650. Net return +1.8%.” Only at that level is there a pattern to see.
4. Never Trust an AI’s Stated Confidence #
Should the AI set the size of each order, between $5 and $10, from the “confidence” it reports? The answer from the research: no.
LLMs are very poor judges of their own certainty. Trained to sound decisive, a model can report “99% confident” even while making things up. Let it size its own orders and sooner or later it will put the most money on exactly the wrong trade.
- My customization: keep fixed-DCA discipline in the execution layer. A fixed rule in code sets the amount per order, and the AI cannot change it.
5. Let AIs Argue Past Two Rounds and They Start Nodding Along #
I first assumed that the longer AIs argued in a chat room, the closer they would get to the truth. In practice, research shows that past the second round they start agreeing with each other.
The cause is training: models learn to agree and keep conversations pleasant, so one side gradually gives in, or both repeat the same point in new words.
- My customization: cap the debate at exactly two rounds.
- Round 1 (blind): the camps write their reports apart, unseen by each other. Whoever reads another view first tends to write around it, an effect called anchoring, which isolation prevents.
- Round 2 (cross-examination): each side may point out exactly one logical hole in the other’s case, and repeating round one is banned.
- On a tie: if the data is too noisy to pick a winner, the research manager may not split the difference. It must apply a prewritten tie-breaker: move the take-profit level closer because the market is risky, or follow the SMA 200’s direction.
All five points say one thing: some jobs should not go to an LLM. Next is the fence I built so it cannot do them.
III. The Architecture: AI Writes the Call, Code Holds the Money #
After running it a while, I settled on one rule: never let a system that runs on probability hold money. An LLM picks each next word by probability, so the same question can get two different answers. The only way out is to contain that uncertainty inside plain code. Plain code here means code a person writes line by line, where the same input always gives the same output.
Like the original, the project has 5 steps and 12 agents, each reworked for real use.
The system has two independent halves: the AI Brain analyzes, and the Execution Hands place orders. This is the key point of the post: the AI half can never touch money. Think of the payday gold buyer again: friends arguing about prices might talk them into skipping a month. Still, the amount is fixed in advance, and no friend holds their bank card.
1. AI Brain: 5 Steps, 12 Agents #
Instead of writing one giant prompt and praying, I use LangGraph to coordinate the agents. LangGraph is a library that chains LLM calls into a process shaped like a flowchart. Each node on the chart is one job, and the paths between nodes are plain code I wrote, not the model’s choice. The model has freedom only inside a node.
Step 1 — Gather data. Four agents run in sequence:
Market Analyst: fetches prices and computes indicators with yfinance and stockstats, as in Section II.2.
News Analyst: pulls macroeconomic news, meaning interest rates, inflation and central bank policy. It filters out noise, keeping only events that could set a 1-to-4-week trend.
Social Analyst: gauges crowd sentiment to guess whether small investors want to buy or sell. It uses the fear and greed index, a score built from price swings and online buzz, plus talk on platforms like StockTwits, a social network for investors.
Fundamentals Analyst: pulls company ratios such as P/E, PEG and ROE, based on financial statements, to judge whether an asset is cheap or expensive against its real value.
I still coded this node to keep the original author’s architecture intact. But tokenized gold is not a company and has no financial statements, so for XAUT I skip it.
Step 2 — Debate. Two rounds as in Section II.5: independent writing from step 1’s data, then cross-examination for logical holes or misread data. Finally, the research manager condenses the strongest arguments into a neutral report, the compass for the decision stage.
Step 3 — Plan. From that report, the Trader agent proposes a concrete plan: entry, stop-loss and take-profit levels. The entry is the price at which to buy. A stop-loss automatically sells at a preset lower price so the loss stops growing. These levels follow the price’s real swings, not a vague “should buy” signal.
Step 4 — Manage risk. Three agents review the plan with three appetites: one favors returns, one favors protecting capital, and one sits in between. If they conflict or the plan piles in abnormally, the Portfolio Manager agent resizes or cancels the order.
Step 5 — Save the result. The AI Brain knows nothing of the real wallet balance. The Portfolio Manager’s last job is to write one JSON file to the database with exactly one decision: UP, DOWN or STAY OUT, plus explanatory notes. JSON is a text-based data format any software can read. That is all. No path leads from here straight to the exchange.
2. Execution Hands: Plain Code Holds the Money #
This half is a Python program written entirely in plain code, connected to Binance, a large crypto exchange. It holds the API key, a secret code that lets software place orders on the account owner’s behalf. It reads the AI Brain’s JSON file and decides whether to send an order.
Its heart is an automatic circuit breaker, like the one in a home’s electrical panel: past the limit it trips, and only a person can switch it back on. However confident the AI is, if total assets fall more than 15% below their highest point, the breaker trips. All trading stops immediately until a person reviews it. Suppose the account once reached $1,000: below $850, the breaker trips.
That is the crux: plain code uses hard logic to keep the AI half under control. The AI may be wrong, and certainly will be. But how wrong is capped by a number in code, not by whatever the model wrote that day.
Honestly, I have not dug deep into this execution layer; it sits at the most basic level needed for safety. I will probably rewrite it the night a fairy godmother visits my dreams with a better design.
IV. A Report That Reads Well Is Not a Profitable One #
Reading the daily reports from this agent lineup, I find the reasoning solid and credible. Had I studied the price charts and macro news myself, I doubt I would conclude much differently. Flattering, until I noticed it only proves the AI reasons like me, not that this reasoning makes money.
So, plainly: “the report reads sensibly” and “the strategy is profitable” are two different claims, and the first does not prove the second. The system is still on trial. Markets always bring surprises, especially slippage.
Slippage is when an order fills at a different price than the one you saw, common when few people are trading or prices move fast. Only time will tell whether this system makes or loses money. And this post is an engineering log, not investment advice.
Whatever the result, the project taught me one thing: AI in a product works because you draw a boundary, not because you pour everything into one prompt and cross your fingers. The plain-code blocks (the flowchart, the circuit breaker, the data-fetching layer) contain and steer the probabilistic part and keep it disciplined. The AI half handles comprehension; the code half handles not losing money.
If your team is adding AI to a product, ask the engineers: “If the AI is completely wrong, which code stops it, and what is the maximum damage?” For MdevTrade, the answer is the circuit breaker and that 15% below the peak.
The full source is public at: https://github.com/vinhmdev-com/mdevtrade
Special thanks to the author of the original TradingAgents project at https://github.com/TauricResearch/TradingAgents for the inspiration and the architectural ideas.