How I Built an Automated Forex Trading Bot with AI in MQL5
I used to think only quantitative hedge funds and veteran C++ programmers could build automated trading systems — until I built an automated forex trading bot with AI inside MetaTrader 5 MQL5. This stop-and-reverse Expert Advisor removes emotional mistakes, trails its stop-loss on every tick, and instantly flips positions to catch reversals.
In this guide, you will get the exact prompt template I used to generate production-ready MQL5 code with Claude and ChatGPT, plus the broker safety checks that keep live orders valid: automatic stop-level detection, auto-retry on rejection, and freeze-level protection. The full source is on GitHub.
If you are new to AI-assisted trading development, I also wrote a brutally honest guide to building AI trading bots that covers the discipline side of the process before you write a single line of code.
How the Flip-Flop Strategy Works
I built this bot to remove emotional mistakes like hesitating during breakouts or moving stop-losses during losing streaks.
The algorithm connects to your broker’s live feed, tracks every market tick, and executes trades instantly without second-guessing.
[Market Price Moves]
│
Is a position open?
/ \
[YES] [NO]
/ \
Trail the Stop-Loss Open opposite trade
behind market price. to catch reversal.
The “Always in the Market” Logic
The strategy follows a simple price cycle:
- Initial Entry: The bot immediately opens a market position (like a BUY) with a tight 10-point stop-loss right behind it.
- Dynamic Trailing: When the trade moves into profit, the bot recalculates the safety level on every tick and moves it forward to protect gains.
- The Instant Reversal: When price reverses and hits the stop-loss, the position closes. The bot immediately opens an opposing SELL order to ride the downward move.
This perpetual stop-and-reverse loop means the bot is never “out” of the market — it simply flips direction. The execution layer relies on the official MQL5 CTrade library, the same approach I detailed in my sovereign MT5 trading bot write-up, which compares native MQL5 against a Python-driven harness for the same terminal.
Prompting AI for Production-Ready MQL5 Code
Asking an AI to “build a profitable bot” yields broken, generic code. AI models write far better software when you give them strict rules, clear library choices, and explicit error-handling steps.
The Developer Prompt Template
Here is the exact prompt structure I used to generate the Expert Advisor:
System Prompt: “Act as an expert MQL5 algorithmic developer. Write a complete MetaTrader 5 Expert Advisor based on these specifications:
- Strategy: Perpetual Stop-and-Reverse without a fixed take-profit.
- Trade Execution: Use the official MQL5 CTrade Standard Library with synchronous execution.
- Trailing Stop: Update tick-by-tick only when price advances favorably by at least half a tick size.
- Broker Safeguards: Read dynamic limits using SYMBOL_TRADE_STOPS_LEVEL and SYMBOL_TRADE_FREEZE_LEVEL.
- Error Handling: If an order triggers TRADE_RETCODE_INVALID_STOPS, widen the stop-loss dynamically and retry up to 10 times.
- Volume & Price: Normalize prices to tick size and lot sizes to broker volume steps.”
The same prompt-engineering discipline applies when I build algorithmic trading pipelines with LLM sentiment — precise constraints turn a chatbot into a compiler for your trading logic.
Source Code & GitHub Repository
To keep this guide clear and focused on the core strategy, I host the full source code on GitHub.
📦 Download the Source Code: Clone the complete script from my FlipTrader MQL5 GitHub Repository.
3 Critical Safeguards You Must Include
During early tests, live brokers rejected my orders because the raw logic ignored server limits. I added three essential safeguards to fix this:
1. Automatic Broker Stops-Level Detection
Brokers enforce a minimum distance (SYMBOL_TRADE_STOPS_LEVEL) for all stop-loss orders. If you set a 10-point stop on an asset that demands a 30-point gap, your broker will reject the trade immediately.
My EffectiveSLDistance() function checks your broker’s live rules and widens the stop distance automatically to keep orders valid:
double EffectiveSLDistance()
{
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
double stops = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * point;
double dist = InpSLPoints * point;
if(dist < stops)
dist = stops;
return dist;
}
2. Auto-Retrying Rejected Trades
Volatile market moves and wide spreads can trigger a TRADE_RETCODE_INVALID_STOPS error. Instead of shutting down, the bot runs a 10-attempt loop that doubles the safety buffer on every failed try until the broker accepts the order:
for(int attempt = 0; attempt < 10; attempt++)
{
if(!trade.OrderSend(req, res))
{
if(res.retcode == TRADE_RETCODE_INVALID_STOPS)
{
dist = dist * 2; // widen the safety buffer and retry
continue;
}
}
}
3. Modifying Stops Without Server Spam
Sending modifications on tiny micro-ticks can cause brokers to rate-limit your account. The bot only sends an update if the price moves favorably by at least half a tick size, keeping server requests low and efficient:
if(pos.PositionType() == POSITION_TYPE_BUY)
{
newSL = NormalizePrice(tick.bid - dist);
if(curSL == 0 || newSL > curSL + tickSize / 2.0)
improve = true; // only modify when price really advanced
}
Realistic Expectations: Spreads, Slippage, and Market Regimes
An automated bot guarantees discipline, but you still have to manage trading costs.
The Cost of Spreads
Tight trailing stops create frequent trades. On a standard account with a 1-pip spread, flipping positions every 2 pips gives up 50% of your gross movement to broker fees.
Best Practice: Run this strategy on Raw Spread / ECN accounts with zero markups, using a low-latency Virtual Private Server (VPS) close to your broker’s trade servers. The same cost-awareness applies when you evaluate forex prop firms and their fee structures.
Market Regimes
- Trending Markets: When price breaks out into a strong trend, the trailing stop locks in steady profits as the move extends.
- Consolidation & Chop: In tight sideways ranges, rapid flips cause frequent small losses as price whips back and forth.
If you prefer to trade the daily bias manually instead of running a fully automated loop, my intraday forex trading journal framework documents how I combine session liquidity and structure for discretionary entries.
Frequently Asked Questions
How do I install this bot in MetaTrader 5?
Open MT5 and press F4 to open the MetaEditor development environment. Create a new Expert Advisor file, paste the code from GitHub, and click Compile. Your compiled bot will appear in the MT5 Navigator panel, ready to drag onto any chart.
Can I run this same bot on stocks or crypto?
Yes, but adjust your settings first. High-volatility assets like Bitcoin will hit a tight 10-point stop immediately, so you need a much wider stop distance. For stock equities, watch out for weekend market closures, since opening price gaps can jump past your stop-loss.
What is the best way to test this system safely?
Run the bot on a free demo account first. You can also backtest historical data across different market conditions using the MetaTrader 5 Strategy Tester before risking real funds.
Get weekly market breakdowns like this in your inbox. No hype, no shilling — just data and analysis. Subscribe below.
Disclaimer: Algorithmic trading involves high risk. This guide is for educational purposes and does not constitute financial advice.
Found this valuable? Share the insight.