Black Friday: all 12 tools. Until 1 December.Black Friday $606.98 one by one

$606.98 one by one $49 once Save $557.98Get the SuiteGet it
ProEA Lab · MT5, TradingView and trading research · Evidence standards
AI

How to Build a Trading Bot With AI (ChatGPT or Claude)

ChatGPT or Claude can write a working trading bot in an afternoon, but working code is not an edge. Here is the build workflow, the five things AI leaves out, an audit for the failures that stay silent, and the four decisions you keep.

PL · 13 min readUpdated
A row of robots churning out endless code printouts beside a lone trader on a narrow bridge over a chasm, facing a citadel of gold and a rising chart on the far side.

To build a trading bot with AI, write the rules yourself, have ChatGPT or Claude turn them into code and a test harness, then judge the result on data the model never saw. The model can produce working MQL5, Pine or Python in minutes. It can't tell you whether the strategy makes money after costs, and a bot that compiles and backtests well hasn't answered that question yet.

So the job splits in two. The AI does the building: code, test harnesses, refactors, reports. You do the judging: the edge claim, the costs, the verdict and the decision to go live. (For chart reading, news and journal review rather than code, see how to use AI for trading.)

The AI build loop as a numbered recipe: 1 hypothesis, 2 clean spec, 3 AI scaffolds the code, 4 AI builds the validator, 5 validate behind the wall, 6 read the failures, 7 small forward test — each step tagged AI or YOU.
The build loop. The model does the building; you keep the verdict.

Can AI build a profitable trading bot?

Not from a prompt. AI writes code; it doesn't supply an edge. Ask for "a profitable gold scalping EA" and you'll get the most plausible-looking scalping EA the model can produce, inputs and comments included. If the idea underneath has no edge after costs, you now have a clean, fast expression of no edge.

The US Commodity Futures Trading Commission put it in a title: Customer Advisory: AI Won't Turn Trading Bots into Money Machines, issued with a press release on January 25, 2024 (both checked 2026-10-11). It warns that "AI technology can't predict the future or sudden market changes," and lists promises of unreasonably high or guaranteed returns as a red flag.

A bot has to pass three gates:

GateWhat it provesHow much AI helps
It runsThe code compiles, loads and can send ordersNearly all of it
It backtests wellOne historical sample looked good under the tester's assumptionsA lot, which is the problem
It survivesIt holds up out of sample, on your broker, after costs, in conditions it wasn't built onOnly as the builder of the tests

AI gets you through the first gate almost for free and makes the second easy to produce. The third is the only one that pays, and generating code can't skip it.

What does AI leave out of a trading bot by default?

Five layers separate a backtest from a live account. A model can write every one of them, but a short prompt rarely asks for them, so they're usually missing. Each is invisible in the tester and expensive live.

  1. Costs. Spread, commission, slippage and swap on every round trip. A bot written for a frictionless market overstates every result. The spread tax walks through the arithmetic.
  2. Broker reality. Symbol suffixes (XAUUSD.m against XAUUSD), digits, the minimum stop distance, the freeze level, the lot step and the fill modes the server allows. In MT5 these are symbol properties such as SYMBOL_TRADE_STOPS_LEVEL, SYMBOL_TRADE_FREEZE_LEVEL, SYMBOL_VOLUME_STEP and SYMBOL_FILLING_MODE (MQL5 symbol properties, checked 2026-10-11). Code that ignores them can work in the tester and fail on your account.
  3. Time and events. News releases, rollover, weekend gaps, session opens and thin hours, when spreads widen. A bot that ignores the clock trades all of them the same way.
  4. Execution failure. Requotes, rejections, partial fills and lost connections. The tester assumes the order happened. Live, the server answers with a return code such as TRADE_RETCODE_REQUOTE (10004), TRADE_RETCODE_REJECT (10006), TRADE_RETCODE_DONE_PARTIAL (10010) or TRADE_RETCODE_CONNECTION (10031) (MQL5 trade return codes, checked 2026-10-11), and the bot has to read it. MT5 EA not taking trades covers what the codes mean.
  5. Kill switches. A maximum daily loss, a drawdown halt, an exposure cap, a limit on open positions, a spread halt: rules that turn the system off before it empties the account.

The catch is circular. You have to know these five exist to ask for them, and that's exactly what a beginner leaning on AI doesn't know yet. Put the list in your first prompt.

A tall gap between 'Backtest P&L (looks great)' at the top and 'Live P&L (reality)' at the bottom, filled by five stacked blocks: cost modelling, broker reality, time and events, execution failure, risk and kill-switch — each marked 'AI omits by default'.
Everything the backtest skipped, the live account pays for.

How do you build a trading bot with ChatGPT or Claude?

The workflow is the same whichever model you use: seven steps, and the model does the building in only some of them.

1. Write a hypothesis, not a wish

"Build me a profitable bot" isn't a hypothesis. One falsifiable sentence with a reason to exist is, for example: "On major FX pairs, a pullback into the prior day's value area tends to revert within the session, after costs." The AI can brainstorm candidates. You pick one and make it precise enough to be proven wrong.

2. Turn it into a spec

Entry, exit, stop, sizing, instruments, session, regime filter, cost model, what invalidates the idea and when you'll review it. A good spec is one a stranger could implement and get the same trades. Use the AI to find the gaps ("what's ambiguous in this rule?"), not to fill them with guesses.

3. Have the AI scaffold the code

Ask for the implementation with the risk logic in its own module and every risk value left as an explicit input. Then read it. Code you haven't read is a black box you typed into existence. If you're moving a TradingView strategy to MT5, Pine Script to MQL5 covers what has to match between the two.

4. Have the AI build the validator

This is the step most people skip, and the best use of the model. Instead of asking it to improve the strategy, ask it to build the machinery that tries to kill it: an out-of-sample splitter, a walk-forward harness, a cost-stress run, a split by market regime, a test of neighbouring parameter values, and a report of trade count, expectancy, worst drawdown and longest flat stretch. That kind of harness is tedious to write by hand, which is why it so often gets skipped in favour of a single backtest. The model removes that excuse.

5. Validate behind the wall

The model that wrote or tuned the strategy never sees the data used for the verdict, and never gives the verdict. Lock the out-of-sample period away before step 3. The data decides.

The reason is overfitting at the speed of conversation. Every "add a filter", "tune the period" or "smooth out that drawdown" aimed at the same backtest fits the bot more tightly to that sample, and the model will help, because a smoother curve looks like what you asked for. Do it often enough and the best-looking version is simply the luckiest one, the search problem behind AI backtest overfitting.

A data timeline split by a red dashed wall: the in-sample region on the left is where AI may tune, scaffold and explore; the out-of-sample region on the right is labelled AI never sees it and never scores it.
Generation on one side, judgment on the other. The model stays left of the wall.

6. Read the failures

Expect most ideas to die at step 5. That's the filter working. Here the AI is useful again, for the post-mortem: where did it lose, in which regime, did costs flip the sign, did neighbouring settings fall apart? Ask "why did this fail, and is any hypothesis still worth testing?" Never ask it to make the backtest pass.

7. Forward test small

Only a survivor earns this: a demo or small live test on your own broker, at a size you can afford to lose, with stop rules written before it starts. Decide in advance how many trades you'll need before you judge it; how many trades to test a strategy explains why no single number fits every strategy. Expect live results to differ from the backtest in either direction; EA backtest vs live results shows how to compare them fairly.

Every prompt asks the model to build, explain or inspect. The moment a prompt asks whether the strategy is good, you've handed the model the one job it shouldn't have.

How do you audit the code AI wrote?

Read the lines that touch money first: where the bot sizes a position, sets the stop, sends, modifies and closes orders, handles errors and stops trading. Then look for five failures that run cleanly in a demo and only show up live.

1. Swallowed errors

A catch-all block around a risky call, or an order result nobody checks. The call fails, the bot carries on, and nothing tells you. For every order call, ask: if this fails, does the bot stop, alert you, or keep trading blind?

2. Hallucinated functions

The model calls a function or parameter that doesn't exist, or doesn't behave the way its name suggests. If the code won't compile, you'll notice. The dangerous case compiles and does the wrong thing: the wrong price, the wrong order type, the wrong unit. Check every platform call you don't recognise against the official documentation.

3. Money math off by a decimal

Sizing mixes units, and one wrong unit can multiply risk by ten without changing how the backtest looks, because the bot sizes wrongly on every trade. Here is a hand check with the formula our position size calculator uses, lots = risk ÷ (stop in pips × pip value per lot):

  • A $10,000 account risking 1% risks $100. On EURUSD a standard lot is 100,000 units and a pip is 0.0001, so one pip on one lot is worth $10 in a USD account. With a 50-pip stop: 100 ÷ (50 × 10) = 0.20 lots.
  • MT5's SYMBOL_TRADE_TICK_VALUE is the value of one tick, the price step in SYMBOL_TRADE_TICK_SIZE, not of one pip. On a five-digit EURUSD quote a tick is 0.00001, worth $1 on one lot. Code that divides by that tick value while measuring the stop in pips gets 100 ÷ (50 × 1) = 2.00 lots, and the 50-pip stop then loses $1,000: 10% of the account instead of 1%.

Run one calculation like this by hand, with your broker's numbers, before the bot trades.

4. No kill switch

Unless you ask for one, a generated bot can easily ship with an entry, an exit and nothing else: no daily loss limit, no exposure cap, no halt after repeated order failures. Write the brake yourself, and make sure you understand how it works.

5. Live-only edge cases

Partial fills, a reconnect that sends a duplicate order, a restart that forgets an open position, a symbol that stops quoting, a spread that blows out at the open. A backtest seldom reproduces these, so the happy path passes and the code that handles the rest never runs. Break the bot on purpose on a demo account: disconnect it mid-trade, force a rejected order, restart it while it holds a position. It should fail safe.

A stylized dark code panel with five highlighted zones labeled swallowed error, hallucinated function, lot-size math, missing kill switch, and live-only edge case.
Each one can run clean in a demo and only show up live.

One more check belongs to the data rather than the order code: does the bot read anything it couldn't have known at the time, such as the close of a bar that hasn't finished or an indicator that repaints? A backtest with that bug looks excellent and can't be traded. Look-ahead bias lists the common leaks and how to test for them.

The same audit applies to a bot you buy instead of build. If you can't read it, you can't run these checks; do forex EAs actually work covers what to ask a seller.

What does research say about AI-written code?

The two studies below are general code-security research, not trading research, so read them as a caution about AI-written code, not a measure of trading bots.

  • Pearce and colleagues had GitHub Copilot complete 89 security-relevant scenarios, producing 1,689 programs, and found about 40% of them vulnerable (Asleep at the Keyboard?, IEEE Symposium on Security and Privacy 2022, checked 2026-10-11).
  • In a user study by Perry and colleagues, participants with an AI assistant wrote significantly less secure code than those without one, and were more likely to believe their code was secure. The participants who trusted the AI less and engaged more with the language and format of their prompts produced fewer vulnerabilities (Do Users Write More Insecure Code with AI Assistants?, ACM CCS 2023, checked 2026-10-11).

A trading bot is code wired to your money, so a defect there becomes a silent risk bug. Note the last finding: the people who questioned the output did better.

The hostile audit prompt

Paste the bot into a fresh chat with this prompt. The model won't be the final auditor, but it's good at finding holes in a happy path once you tell it to look.

You are a hostile reviewer auditing a trading bot you did NOT write.
Assume it runs unattended with real money. Find every way it fails
SILENTLY. Do not praise it. Do not rewrite it yet. Cite line numbers.

1. MONEY PATH: list every line that sizes a position, sets risk, sends,
   modifies or closes an order, places a stop, or disables trading.
   Explain each in plain English.
2. ERRORS: find every swallowed error or unchecked order result.
   Say what the bot does after each failure.
3. ORDER LIFECYCLE: mark HANDLED / PARTIAL / MISSING for rejected order,
   requote, partial fill, disconnect, reconnect, duplicate order,
   restart with an open position, symbol stops quoting, spread spike.
4. MONEY MATH: show the sizing formula. Check equity, risk %, stop
   distance, pip vs point vs tick, tick value, contract size, lot step,
   min/max lot. Show any path where it risks more than intended.
5. KILL SWITCH: max daily loss, max open risk, spread halt, stop after
   repeated failures. If there is none, write NO BRAKE.
6. DATA: does it read anything it would not have in real time
   (forming bar, same-bar close, repainting indicator, full-sample
   statistic)? Flag possible look-ahead.
7. API: list every function or parameter you are not sure exists and
   behaves as named. Mark each VERIFY AGAINST OFFICIAL DOCS.
8. VERDICT: DO NOT RUN / DEMO ONLY / FIX BEFORE LIVE / DEFENSIBLE,
   plus the single change that most reduces the risk of a silent loss.

Then check what it finds yourself.

Which decisions should you never hand to AI?

Four. The model can help with the work around each one, but the call stays with you.

The callWhat AI can doWhy it stays yours
The edge claimSuggest hypotheses, implement them, explain why they sound plausible"This has an edge" is a conclusion from validation, not a sentence the model writes
The cost assumptionsAdd cost inputs and stress runsIt simplifies costs away unless told otherwise; you set them, pessimistically, from your broker
The validation verdictBuild the gate and summarise the resultThe thing being judged can't also be the judge, least of all on data it helped fit
The go-live callDraft the checklistSize, stops, the kill switch and whether real money is exposed have consequences the model doesn't bear

Hand AI any of those four and you don't have an AI-assisted system; you have an unsupervised intern with your account password. Letting an agent place trades by itself makes the last call permanent; AI trading agents covers what changes once a model has broker access.

What does an AI build session look like, start to finish?

Here is an illustrative afternoon, with no results attached, because the point is the process.

You start with the value-area pullback idea from step 1 and ask the model to turn it into a spec. It points out that "value area" and "within the session" are undefined, so you define them. It scaffolds the EA with a separate risk module, and in a second chat builds a harness that keeps the most recent stretch of data locked, reruns everything at double the spread and reports results by volatility regime. You read both before running anything; how to backtest an EA in MT5 covers the tester settings.

You run the in-sample test, then the locked period with costs on. Say it dies on costs. The post-mortem shows the bounce only held in quiet conditions and gave everything back to the spread when the market trended. You either narrow the hypothesis to quiet sessions, which makes it a new idea that needs data the model hasn't seen, or you drop it. Retesting the narrowed version on the period you already looked at would quietly break the wall.

A version that survives the locked period, the walk-forward and the cost stress earns a small forward test, nothing more. You didn't ask the model for a winner. You used it to test ideas faster and more honestly, so the one that survives means something.

Disclosure

We sell trading tools as source code, including MT5 expert advisors and Pine indicators, and we use AI to build them in the way this guide describes. Nothing here is financial advice or a promise of results: an AI-built bot, ours included, can lose money, and a backtest describes the past under stated assumptions. If someone sells you an "AI trading bot", ask to see the logic, the cost assumptions, the risk layer and a sample you can check yourself.

Frequently asked questions

Can ChatGPT build a profitable trading bot?

It can write a working bot, but not an edge. Code that compiles and backtests well still has to hold up on data it never saw, at your broker's costs and with live execution. The CFTC's advisory on AI trading bots warns that AI can't predict the future or sudden market changes.

Is ChatGPT or Claude better for coding a trading bot?

We haven't benchmarked them on trading code, so we don't rank them. Both can draft MQL5, Pine Script and Python, and either can call a function that doesn't exist. The workflow and the audit on this page apply to whichever model you use.

Can AI write an MT5 expert advisor in MQL5?

Yes, it can draft one. Compile it, check every platform call against the MQL5 documentation, make sure it reads the server's return code after every order, and test it in the Strategy Tester and on a demo account before any real money goes in.

How do I stop AI from overfitting my trading strategy?

Lock an out-of-sample period away before you start, never show it to the model, and stop asking the model to improve results on the same backtest. Use it to build the validator, such as a walk-forward harness and a cost-stress run, not to tune the curve.

What should I check before running an AI-written trading bot live?

Read the lines that size positions, place stops and send orders. Look for swallowed errors, functions that may not exist, sizing math in the wrong unit, a missing kill switch and unhandled live cases such as partial fills and reconnects. Check one position size by hand, then break the bot on purpose on a demo account.

Is AI-generated code safe to trade with?

Not without review. In one general code-security study, about 40% of 1,689 programs that GitHub Copilot generated across 89 scenarios were vulnerable. That wasn't trading code, but a trading bot turns a defect into a money bug, so read and test the code first.

Can I let an AI trading bot run my account on its own?

Only after it has passed validation and a small forward test, and only inside limits you set yourself: position size, a daily loss limit and a kill switch. Autonomy doesn't create an edge. It repeats whatever the bot does, good or bad, without asking you.

Continue reading

AI Trading Agents: What They Can Do With Broker Access, and the Risks

Robinhood, Alpaca and ThinkMarkets now let an AI assistant place orders in a real brokerage account. Here is what an agent can do with that access, what the brokers and eight members of Congress say about the risks, and how to set one up so that a mistake stays small.

Oct 11 · ProEA Lab

A hooded child meditating, calm at the center of a rainbow energy mandala, ringed by green-eyed clockwork machines in a dark tech cathedral — the human still at the center of the machine swarm.

TradingView MCP Server: Official vs Community

TradingView's official MCP server gives Claude delayed market data, the screener, watchlists and price alerts on Essential plans and up. A community server drives TradingView Desktop and can compile Pine. How to connect each one, and where each can hurt you.

Oct 3 · ProEA Lab

Flow diagram: an AI assistant reaches TradingView through the official server (delayed quotes and bars, screener, watchlists, price alerts) or through a community server and debug port 9222 to TradingView Desktop (Pine, Strategy Tester, chart control). Cover titled TradingView MCP: official vs community.

How to Use AI for Trading: What ChatGPT and Claude Can and Can't Do

Use ChatGPT or Claude as a reviewer, a rule-keeper and a research assistant, not as a forecaster. Six jobs, what AI can and can't do in each, the evidence behind the limits, and three prompts to copy.

Oct 11 · ProEA Lab

A child floats calmly cross-legged, eyes closed, at the centre of glowing orbital rings dotted with coloured nodes, while towering green machines with glowing eyes reach in with giant mechanical hands: the trader keeps the decision while the machines do the work around it.