MQL5 & MQL4 AI Code Prompts — Generate EAs & Indicators That Actually Compile

Proven prompt templates for ChatGPT, Claude, DeepSeek, and Gemini. From EA skeleton to prop firm compliance to indicator development — copy, paste, compile.

Vague prompts produce broken code. Structured prompts produce production EAs.

Why Vague MQL5 Prompts Fail — And What Works Instead

Traders open ChatGPT and type: "Write me an MQL5 EA that trades the EMA crossover." The output arrives in seconds. It looks impressive. But when you paste it into MetaEditor, it fails to compile. When you fix the errors, it opens positions without stop losses. When you add stops, the lot sizing is wrong. When you fix the lots, it crashes because the indicator handles leak memory.

This is not the AI's fault. It is a specification problem. A one-sentence prompt gives the AI no information about your broker's execution mode, minimum stop distance, session filters, spread tolerances, or drawdown limits. The AI fills in the gaps with plausible guesses — and those guesses are where accounts get destroyed.

The fix: the 6-component MQL5 prompt framework. Every production-ready prompt must define the AI's role, required libraries, input parameters, entry/exit logic, risk management rules, and the output format. Skip one component, and the generated code has a gap you'll discover at the worst possible moment — usually during a prop firm challenge.

The 6-Component MQL5 Prompt Framework

Every prompt in this guide follows this structure. Apply it to your own strategy ideas.

01

Role Definition

Tell the AI exactly who it is. "Act as a Senior MQL5 Developer with 10+ years experience writing MetaTrader 5 Expert Advisors for institutional clients." Role defines quality expectations.

02

Required Libraries

Specify standard MQL5 includes. "#include <Trade\Trade.mqh> for order execution. #include <Indicators\Indicators.mqh> for indicator handles." Prevents custom unsafe functions.

03

Input Parameters

Define every extern/input variable: MagicNumber, LotSize, StopLoss, TakeProfit, indicator periods, session times. All configurable, no hard-coded values.

04

Entry/Exit Logic

Write exact conditions in bullet points. "Buy when: RSI(14) < 30 AND price > 200 EMA AND volume > 20-bar average AND no news in 30 min." Multi-condition confluence.

05

Risk Management

Dynamic, not fixed. "SL = 1.5x ATR(14). TP = 2x SL distance. Max 1% risk per trade. Daily loss limit 3%. Check broker StopsLevel before order." Saves accounts.

06

Output Format

Request complete compilable .mq5 file. Specify OnInit/OnDeinit cleanup. Request comments. "Write the full code. No placeholders. No '...rest of the code'. Complete file."

Which AI Model for MQL5 Code Generation?

ChatGPT (GPT-4o)

Best Overall ★★★★★

Strongest MQL5 syntax understanding. Cleanest compilable code. Best for full EAs, indicators, and complex logic. Understands MetaTrader 5 build differences.

Claude

Risk Logic ★★★★☆

Never breaks rules. Perfect for risk management functions, position sizing, and drawdown monitoring. Produces well-commented, readable code.

DeepSeek

Debugging ★★★★☆

Best for error analysis. Paste your non-compiling code, it finds the exact errors. Excellent at MQL4-to-MQL5 conversion. Free, unlimited.

Gemini

Quick Scripts ★★★☆☆

Fast for simple indicators and utility scripts. Less reliable for complex EAs. Good for brainstorming code architecture and generating test scaffolds.

Pro workflow: Generate the EA with ChatGPT, validate risk logic with Claude, debug any issues with DeepSeek, and use Gemini for quick utility scripts.

🔧 MQL5 Code Generation Prompt Templates

EA Skeleton / Structure Prompt

Master Prompt #1 — Production-Ready EA Framework

Start every MQL5 project with this. It forces the AI to use standard libraries, set up clean input parameters, and implement proper OnInit/OnDeinit resource management. Never start from an empty prompt.

Act as a Senior MQL5 Developer with 10+ years experience writing trading systems for institutional clients. I need you to create a robust Expert Advisor skeleton that compiles without errors in MetaTrader 5 build 4600+.

CONSTRAINTS:
1. Use the standard #include <Trade\Trade.mqh> library for all order execution. Never write custom OrderSend functions.
2. Use #include <Indicators\Indicators.mqh> for all technical indicator handles.
3. All indicator handles must be initialized in OnInit() and released with IndicatorRelease() in OnDeinit().
4. Do NOT use Martingale, Grid, or averaging-down logic. Every trade must have a hard Stop Loss.
5. No magic numbers — every value must be an input parameter.

INPUT PARAMETERS:
Create user inputs for:
- input int MagicNumber = 123456;
- input double LotSize = 0.01;
- input int StopLoss_Pips = 0; // 0 = use ATR-based dynamic SL
- input int TakeProfit_Pips = 0; // 0 = use Risk/Reward ratio
- input double RiskPercent = 1.0; // % of account per trade
- input double ATR_Multiplier_SL = 1.5;
- input double RewardRiskRatio = 2.0;
- input int ATR_Period = 14;
- input int MaxSpreadPoints = 10;
- input bool UseNewsFilter = false;
- input int NewsMinsBefore = 30;
- input int NewsMinsAfter = 30;

STRUCTURE:
- Define all global variables at the top with clear comments.
- OnInit(): Initialize indicator handles, set magic number and trade settings, return INIT_SUCCEEDED or INIT_FAILED.
- OnDeinit(): Release all indicator handles — use IndicatorRelease() for every handle.
- OnTick(): Check new bar. Check spread. Check news. Check drawdown limits. Execute entry logic. Manage open positions.
- OnTrade(): Handle trade events if needed.

OUTPUT: Write the complete, compilable .mq5 file. Every function must have proper error checking. Include descriptive comments. No placeholder code — every function must be fully implemented with correct MQL5 syntax.
Entry Logic / Signal Generation Prompt

Master Prompt #2 — Multi-Condition Confluence Entry

Never ask for a single-indicator strategy. Professional trading requires confluence. This template forces the AI to combine trend, momentum, and volume filters into one valid signal.

Now implement the OnTick() trade entry logic for the EA skeleton above. A trade signal is valid ONLY when ALL conditions are met simultaneously. Use a NewBar check so evaluation happens once per candle close.

BUY SIGNAL (ALL 4 conditions required):
1. TREND FILTER: Price (current close) must be ABOVE the 200-period Exponential Moving Average on the current timeframe.
2. MOMENTUM FILTER: RSI(14) must be below 35 (oversold territory, indicating potential reversal upward).
3. VOLUME FILTER: Current bar tick volume must be at least 20% higher than the simple average volume of the last 20 bars.
4. NEWS FILTER: If UseNewsFilter is enabled, no high-impact news event must be scheduled within NewsMinsBefore minutes before or NewsMinsAfter minutes after the current time.

SELL SIGNAL (ALL 4 conditions required):
1. TREND FILTER: Price must be BELOW the 200 EMA.
2. MOMENTUM FILTER: RSI(14) must be above 65 (overbought).
3. VOLUME FILTER: Same — volume 20% above 20-bar average.
4. NEWS FILTER: Same as above.

ADDITIONAL LOGIC:
- Only open a trade if no position already exists for this symbol and MagicNumber.
- Check if the current spread is below MaxSpreadPoints before placing any order.
- Calculate Stop Loss using ATR_Multiplier_SL × ATR(ATR_Period) — convert to points.
- Calculate Take Profit: SL distance × RewardRiskRatio.

OUTPUT: Write the complete OnTick() function with all signal checks, trade execution, and error handling.
Risk Management Prompt

Master Prompt #3 — Dynamic Risk & Position Sizing

This is where you save your account. Never let AI hard-code a fixed SL. Dynamic ATR-based stops + proper lot calculation + broker validation.

Rewrite the trade execution function to use dynamic risk management. No hard-coded stop distances. Every risk calculation must be market-adaptive.

RISK CALCULATION:
1. STOP LOSS in points = ATR_Multiplier_SL × ATR(ATR_Period) current value. Convert the ATR value from price units to points using SymbolInfoDouble(_Symbol, SYMBOL_POINT).
2. TAKE PROFIT in points = SL distance in points × RewardRiskRatio.
3. Validate that calculated SL distance is greater than (SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) + SymbolInfoInteger(_Symbol, SYMBOL_SPREAD)). If not, set SL to the minimum allowed and adjust TP accordingly.

POSITION SIZING:
1. Account risk in deposit currency = AccountInfoDouble(ACCOUNT_EQUITY) × (RiskPercent / 100.0).
2. Pip value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE) for 1 lot at current price.
3. Lot size = Account risk / (SL distance in points × pip value). Round to 2 decimals.
4. Validate lot size against SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN) and SYMBOL_VOLUME_MAX and SYMBOL_VOLUME_STEP.
5. If calculated lot < minimum, skip the trade. If > maximum, cap at maximum.

DRAWDOWN PROTECTION:
1. Track daily starting equity at the beginning of each day (first tick of the day).
2. If current equity drops below (daily start × (1 - DailyLossPercent/100)): close all positions, stop trading for the rest of the day.
3. Add an input: input double DailyLossPercent = 3.0;
4. Add an input: input double MaxTotalDrawdownPercent = 15.0;
5. If account drawdown from peak equity exceeds MaxTotalDrawdownPercent: stop the EA completely (set a flag, stop processing OnTick).

BROKER VALIDATION (before every order):
1. Check SymbolInfoInteger(_Symbol, SYMBOL_TRADE_MODE) — only trade if mode allows.
2. Verify account free margin is sufficient: free margin > (lot size × margin required).
3. Use OrderCalcMargin() for accurate margin calculation.

OUTPUT: Complete, compilable trade execution and risk management module with all functions.
Custom Indicator Development Prompt

Master Prompt #4 — Custom Indicator Template

Generate custom MT5 indicators — from simple combined indicators to complex multi-timeframe dashboards.

Act as a Senior MQL5 Developer specializing in custom MetaTrader 5 indicators. Create a custom indicator with the following specification.

INDICATOR TYPE: [Choose: Separate Window / Chart Window]

INDICATOR PROPERTIES:
- #property indicator_separate_window (or indicator_chart_window)
- Set indicator_buffers count
- Set indicator_plots count
- Define indicator_label, indicator_type1 (DRAW_LINE, DRAW_HISTOGRAM, DRAW_ARROW, DRAW_COLOR_LINE, etc.)
- Define indicator_color1, indicator_width, indicator_style

INPUT PARAMETERS:
- input int LookbackPeriod = 14; // Main calculation period
- input int SignalPeriod = 7; // Signal line period
- input ENUM_APPLIED_PRICE AppliedPrice = PRICE_CLOSE;
- input color BullColor = clrDodgerBlue;
- input color BearColor = clrTomato;

CALCULATION LOGIC:
[Describe your specific calculation here. Examples:]
- "Calculate the difference between two MAs and normalize as a percentage of the shorter MA."
- "Calculate RSI divergence — when price makes a higher high but RSI makes a lower high, plot a sell arrow."
- "Calculate the ratio of bullish candle volume to total volume over LookbackPeriod."

ONCALCULATE REQUIREMENTS:
- Properly handle rates_total, prev_calculated for efficient calculation.
- Only recalculate changed bars — do not recalculate the entire history on every tick.
- Set buffer values using array indexing: buffer[i] = value.
- Check for division by zero before any division.
- Check for ArraySetAsSeries() before using array indices.

BUFFER SETUP:
- At least 2 indicator buffers: one for main line, one for signal line.
- Optional: color buffer for multi-color lines, arrow buffer for signals.
- Set indicator_shortname to a descriptive name.

OUTPUT: Complete, compilable .mq5 indicator file. Include all #property declarations. Maintain proper OnInit/OnCalculate structure. Add comments explaining the calculation logic.
Specific Indicator Generator Prompts

Ready-to-Use — Replace the bracketed text

Below are complete prompts for generating specific indicator types. Copy any prompt and replace [BRACKETED TEXT] with your values.

--- RSI DIVERGENCE INDICATOR ---
"Create an MT5 indicator that detects RSI divergence. Plot green up-arrows when: price makes a lower low on the last 2 swing lows, BUT RSI(14) makes a higher low — bullish divergence. Plot red down-arrows when: price makes a higher high, BUT RSI makes a lower high — bearish divergence. Use swing detection with [5] bars left and right for swing point validation. Include buffer for divergence strength — measure the difference between the RSI divergence slopes."

--- MULTI-TIMEFRAME DASHBOARD ---
"Create an MT5 dashboard indicator that displays trend direction for [EURUSD, GBPUSD, USDJPY, XAUUSD] on timeframes [M15, H1, H4, D1] in a grid. Use 50 EMA vs 200 EMA crossover for trend detection. Green cell = bullish (50 above 200). Red cell = bearish. Yellow = within 10 pips of crossover. The dashboard must auto-update on each new bar. Use OBJ_LABEL objects for clean rendering. Include a 'Strength Score' at the bottom — count of bullish timeframes minus bearish timeframes per pair."

--- ATR CHANNEL INDICATOR ---
"Create an MT5 indicator that plots ATR-based support and resistance channels. Upper band = High + (ATR([14]) × [2.0]). Lower band = Low − (ATR([14]) × [2.0]). Midline = (Upper + Lower) / 2. Plot all three as lines. Color the channel fill between upper and lower with 15% opacity. Add breakout arrows when price closes outside the channel."

--- VOLUME PROFILE INDICATOR ---
"Create a volume profile indicator for MT5. For the visible chart range, divide the price range into [20] horizontal zones. For each zone, calculate: total tick volume, percentage of total volume, and number of touches. Mark the Point of Control (POC — zone with highest volume) with a thick horizontal line. Mark Value Area High/Low (zones containing 70% of total volume). Display the volume profile as a horizontal histogram on the right side of the chart."

OUTPUT for each: Complete, compilable .mq5 with proper buffer management, OnInit/OnCalculate structure, and descriptive comments.
Prop Firm Compliance Prompt

Master Prompt #5 — FTMO & Prop Firm Ready EA

Prop firms have strict rules. This prompt adds every required guardrail to any EA — daily drawdown, total drawdown, minimum trading days, news avoidance, and session windows.

Modify the EA to be fully compliant with prop firm evaluation rules (FTMO standard).

COMPLIANCE RULES:
1. DAILY DRAWDOWN LIMIT: input double DailyDDLimit = 4.5; // % of starting day equity. Set slightly tighter than FTMO's 5% for safety buffer.
   - Track the starting equity at 00:00 server time each day.
   - If equity falls below starting × (1 - DailyDDLimit/100): IMMEDIATELY close all positions using PositionClose(). Set a flag to prevent new trades for the rest of the day.
   - At the start of the next day: reset the flag, recalculate starting equity.

2. MAXIMUM TOTAL DRAWDOWN: input double MaxTotalDD = 9.0; // % from peak equity. Tighter than FTMO's 10%.
   - Track the highest equity value achieved (peak equity).
   - If current equity falls below peak × (1 - MaxTotalDD/100): stop EA permanently. Log the violation. Send a notification.

3. MINIMUM TRADING DAYS: input int MinTradingDays = 4;
   - Track which days had at least one trade opened.
   - Log the count of active trading days.

4. NEWS FILTER (ENHANCED):
   - Maintain a list of high-impact keywords: "NFP", "FOMC", "CPI", "GDP", "ECB", "BOE", "BOJ", "Interest Rate", "PMI", "Retail Sales".
   - For each keyword, define a date-time window. If the current time falls within 30 minutes before or 30 minutes after any event: skip all trade entry logic.
   - Store news times in a static array or read from a CSV file placed in the Files folder.

5. SESSION FILTER:
   - input bool UseSessionFilter = true;
   - input int SessionStartHour = 7; // GMT — London open
   - input int SessionEndHour = 17; // GMT — NY close
   - Only allow trades between SessionStartHour and SessionEndHour GMT.
   - Convert server time to GMT using TimeGMT() before comparison.

6. POSITION LIMITS:
   - input int MaxOpenPositions = 1; // Most prop firms require max 1 position at a time
   - input int MaxDailyTrades = 5;
   - Track daily trade count. If MaxDailyTrades reached: stop for the day.

7. WEEKEND FLAT:
   - Close all positions 5 minutes before Friday market close (check for last trading minute of the week).
   - Do not open new positions on Friday after [19:00] server time.

OUTPUT: Add all compliance functions to the existing EA code. Each function must be modular — put compliance checks in a separate CheckPropFirmRules() function called at the start of OnTick(). If any rule is violated, the function returns false and all trade logic is skipped.
Debugging & Error Fixing Prompt

Master Prompt #6 — When Code Doesn't Compile

Paste your broken code + the MetaEditor error list. AI finds and fixes errors other LLMs introduced.

Act as an MQL5 compiler expert. I am pasting an EA that fails to compile in MetaTrader 5 build 4600. Below the code, I will paste the exact error messages from MetaEditor.

YOUR TASK:
1. Read the complete code. Identify every compilation error.
2. For each error, explain WHY it occurred in plain English — was it a syntax error, a missing declaration, a type mismatch, or a deprecated function?
3. Fix every error and return the COMPLETE corrected code. Do not abbreviate sections. Do not write "// rest of the code remains the same." Return the full file.
4. Verify that all indicator handles are properly initialized in OnInit() and released in OnDeinit().
5. Verify that no MQL4-only functions are used (like OrderSend with old parameters). All order execution must use CTrade or the Position/Order classes.
6. Check that all arrays are properly set with ArraySetAsSeries() before being accessed.
7. Verify that OrderCalcMargin() or OrderCheck() is called before any trade execution.

ERROR MESSAGES:
[PASTE YOUR METADITOR ERROR LIST HERE]

EA CODE:
[PASTE YOUR NON-COMPILING .MQ5 CODE HERE]

OUTPUT: Complete, compilable, corrected code. Include a summary of all fixes made.
MQL4 to MQL5 Conversion Prompt

Master Prompt #7 — Upgrade Legacy MQL4 Code

Act as an MQL5 migration specialist. Convert the following MQL4 Expert Advisor to fully functional, modern MQL5 code.

CONVERSION RULES (MANDATORY):
1. Replace all OrderSend() calls with CTrade class methods (trade.Buy(), trade.Sell(), trade.PositionClose()).
2. Replace OrderSelect() loops with PositionSelectByTicket() for open positions. Use HistorySelect() + HistoryDealGetTicket() for closed trades.
3. Replace all old indicator functions (iRSI, iMA, iMACD, iATR, iBands) with indicator handles:
   - Create handle in OnInit(): int rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, 14, PRICE_CLOSE);
   - Get values in OnTick(): CopyBuffer(rsiHandle, 0, 0, 3, rsiBuffer);
   - Release in OnDeinit(): IndicatorRelease(rsiHandle);
4. Replace MarketInfo() calls with SymbolInfoInteger() / SymbolInfoDouble().
5. Replace AccountBalance() with AccountInfoDouble(ACCOUNT_EQUITY) if using equity-based risk.
6. Replace datetime string parsing with TimeToString() using proper format flags.
7. Replace ObjectsDeleteAll() with proper object cleanup functions.
8. Add proper error handling after every trade operation using GetLastError().
9. Ensure all arrays use ArraySetAsSeries() after CopyBuffer() calls.

MQL4 CODE TO CONVERT:
[PASTE YOUR MQL4 EA CODE HERE]

OUTPUT: Complete, compilable MQL5 .mq5 file. Include comments noting every conversion made. Ensure the converted EA produces identical trading logic to the original MQL4 version.

The Complete Workflow: From Prompt to Live EA

Write the Specification First

Before any AI prompt, define your strategy completely: entry conditions, exit conditions, risk parameters, session filters, pairs, timeframes. A complete spec prevents the AI from guessing — and guessing is where bugs come from.

Generate the EA Skeleton (Prompt #1)

Start with the structure prompt. Get a clean, compilable framework with proper library includes, input parameters, and OnInit/OnDeinit resource management. Compile. Fix any errors. Only proceed once it compiles cleanly with zero warnings.

Add Entry Logic (Prompt #2)

Use the confluence prompt to implement your specific strategy conditions. Paste the existing skeleton code + your entry requirements. The AI extends the code rather than rewriting it.

Add Risk Management (Prompt #3)

The most critical step. Dynamic ATR-based stops, proper lot sizing, drawdown protection. Test on demo with minimum position size for at least 2 weeks before going live.

Add Prop Firm Guardrails (Prompt #5)

If targeting a funded challenge, add the compliance module. Daily DD, total DD, news filter, session limits, position caps. Test against the specific prop firm's rules.

Debug & Iterate (Prompt #6)

Paste compilation errors back to the AI with the debug prompt. Iterate until zero errors. Then backtest, forward test, and only then — live with minimum size.

Common MQL5 AI Code Errors and How to Avoid Them

ErrorWhy It HappensFix in Prompt
Indicator handle not createdAI puts handle init in OnTick instead of OnInit"All indicator handles MUST be created in OnInit()"
MQL4 syntax in MQL5 fileAI trained on mixed MQL4/MQL5 data"Use ONLY MQL5 syntax. No MQL4 functions."
Array out of rangeAI doesn't check array size before accessing"Check ArraySize() before every array access"
Wrong order send parametersAI uses deprecated 4-param OrderSend"Use CTrade class only. Never raw OrderSend."
StopsLevel violationAI ignores broker minimum stop distance"Validate SL against SYMBOL_TRADE_STOPS_LEVEL before order"
Memory leak from handlesAI doesn't release indicator handles in OnDeinit"Release ALL handles via IndicatorRelease() in OnDeinit"

Frequently Asked Questions

Can AI write MQL5 code for Expert Advisors?

Yes. ChatGPT, Claude, DeepSeek, and Gemini can all generate working MQL5 code. Quality depends entirely on your prompt — structured 6-component prompts produce production-ready code. Vague one-sentence requests produce code that compiles occasionally but fails in live markets due to missing risk logic, wrong order handling, or unmanaged indicator handles.

Which AI is best for MQL5 code generation?

ChatGPT (GPT-4o) is the strongest for main EA code — cleanest syntax, best compilation rate. Claude excels at risk management and complex logic structures. DeepSeek is best for debugging and MQL4-to-MQL5 conversion. Gemini for quick indicator scripts. Professional workflow: ChatGPT for main code, Claude for risk validation, DeepSeek for debugging.

How do I write a good prompt for MQL5 code generation?

Use the 6-component framework: (1) Role — Senior MQL5 Developer, (2) Libraries — specify Trade.mqh and Indicators.mqh, (3) Inputs — all parameters as extern/input, (4) Entry/Exit — bullet-point conditions with confluence, (5) Risk — dynamic ATR-based, equity-based lot sizing, drawdown limits, (6) Output — request complete compilable file, no abbreviations.

Why does AI-generated MQL5 code fail to compile?

Top reasons: AI mixes MQL4 syntax into MQL5, doesn't initialize indicator handles in OnInit, uses deprecated OrderSend instead of CTrade, doesn't check StopsLevel before placing orders, or references undeclared variables. The debugging prompt (Master Prompt #6) in this guide fixes all of these. Also see our AI analysis guide for validation methodology.

Can AI prompts generate prop firm compliant EAs?

Yes. Master Prompt #5 adds daily drawdown limits, total drawdown monitoring, news filters, session filters, position limits, and weekend-flat logic. Test the generated EA on demo for minimum 2 weeks before a challenge. Set drawdown limits 0.5% tighter than the prop firm's rules to build in a safety buffer against execution variance.

Can I use these prompts with the free versions of these AI tools?

Yes. All prompts work with free tiers of ChatGPT, Claude, DeepSeek, and Gemini. DeepSeek is fully free with no usage caps — ideal for longer code generation sessions. ChatGPT free tier may limit message count for very long outputs. For complex EAs requiring many iterations, consider ChatGPT Plus or DeepSeek. All your forex prompt templates are free to use.

Need a Custom EA Built from These Prompts?

These prompts will get you 80% of the way. For the remaining 20% — production-grade optimization, ONNX model deployment inside MT5, or a completely custom AI-powered trading system — we build EAs professionally, validated with walk-forward testing and prop-firm compliance out of the box.

Get a Custom EA Quote Forex Prompt Library Free AI Tools Directory
🚀 Invite friends — Earn $5 You both get $5 credit on Go Ad · opencode.ai AI-Powered Coding Agent — Try Free Build apps, fix bugs & ship faster with opencode. Get $5 free credit when you join. Ad · quo.com QuoPhone — $20 Visa Gift Card Free Sign up to Quo, subscribe 3 months, get a $20 Visa gift card. Atif's referral gift for you.