AI EA Builder and Pine Script Generator
Describe your trading idea in plain words and get code for MetaTrader 5, MetaTrader 4 and TradingView.
Sign up and generate codeMQL5 · MQL4 · Pine Script · Runs in your browser

What you can build with AI
Expert Advisor. An automated strategy with entry and exit rules, stop loss, take profit and risk-based position sizing.
Custom indicator. Your own indicator with lines, histograms, arrows, levels and alerts that follow your rules.
Script. A one-off action in the terminal: close all positions, place a grid of pending orders, export trade history to a file.
Changes to existing code. Paste your EA or indicator and say what to change: add a trailing stop, a time filter or a push alert.
Create an Expert Advisor for MetaTrader 5 (MQL5)
Describe entry rules, stops and position sizing for MetaTrader 5. Compile the generated MQL5 file in MetaEditor.
Example request: "Build an MT5 EA using an EMA 20/50 crossover on H1, stops in points and percentage risk."
Expert Advisors and indicators for MetaTrader 4 (MQL4)
For MetaTrader 4, request MQL4 explicitly. Its trading and indicator APIs differ from MQL5.
Example request: "Create an MT4 indicator that colors the Asian, European and American trading sessions."
AI Pine Script generator for TradingView
Create Pine Script indicators or strategies for TradingView. Check them in the Pine Editor and Strategy Tester.
Example request: "Write a Pine v6 indicator with previous-day high and low levels and breakout alerts."
How to create an Expert Advisor in three steps
1. Describe the idea. Name the platform and describe the rules for your EA or indicator.
2. Get the code. The AI writes the whole program and explains what each part does.
3. Test and refine. Compile, run the Strategy Tester and ask for corrections.
Why build your EA here
- In the browser. You do not need to open a terminal or an editor to get the code.
- Three platforms in one place. MetaTrader 5, MetaTrader 4 and TradingView, Pine Script included.
- Plain language. Write the request the way you would explain the task to a developer.
- A conversation, not a form. Refine and rework the code without starting over.
Examples: request and generated code
MT5 EA: EMA 20/50 crossover · mql5
Write a concise and complete MQL5 Expert Advisor for MetaTrader 5. Trade the EMA20/EMA50 cross on closed H1 bars, one position at a time. Use input stop and take-profit points and percentage risk for position sizing. Use the installed standard library. Return only one complete fenced mql5 source file. All comments, identifiers, labels and strings must be English ASCII. Compile-only example.
#property strict
#property version "1.00"
#include <Trade/Trade.mqh>
input int StopLossPoints = 500;
input int TakeProfitPoints = 1000;
input double RiskPercent = 1.0;
input ulong MagicNumber = 205050;
CTrade trade;
int fastHandle = INVALID_HANDLE;
int slowHandle = INVALID_HANDLE;
datetime lastBar = 0;
int OnInit()
{
if(StopLossPoints <= 0 || TakeProfitPoints <= 0 ||
!MathIsValidNumber(RiskPercent) ||
RiskPercent <= 0.0 || RiskPercent > 100.0)
return INIT_PARAMETERS_INCORRECT;
fastHandle = iMA(_Symbol, PERIOD_H1, 20, 0, MODE_EMA, PRICE_CLOSE);
slowHandle = iMA(_Symbol, PERIOD_H1, 50, 0, MODE_EMA, PRICE_CLOSE);
if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
return INIT_FAILED;
trade.SetExpertMagicNumber(MagicNumber);
trade.SetDeviationInPoints(20);
trade.SetAsyncMode(false);
if(!trade.SetTypeFillingBySymbol(_Symbol))
return INIT_FAILED;
// Wait for a new H1 bar rather than trading on attachment.
lastBar = iTime(_Symbol, PERIOD_H1, 0);
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
if(fastHandle != INVALID_HANDLE)
IndicatorRelease(fastHandle);
if(slowHandle != INVALID_HANDLE)
IndicatorRelease(slowHandle);
}
double AlignPrice(const double price, const double tickSize,
const bool roundUp)
{
double ticks = price / tickSize;
return NormalizeDouble(
(roundUp ? MathCeil(ticks) : MathFloor(ticks)) * tickSize,
_Digits);
}
double RiskVolume(const ENUM_ORDER_TYPE type,
const double entry, const double stop)
{
double minimum = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maximum = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
if(minimum <= 0.0 || maximum < minimum || step <= 0.0)
return 0.0;
double loss = 0.0;
if(!OrderCalcProfit(type, _Symbol, minimum, entry, stop, loss) ||
loss >= 0.0)
return 0.0;
double budget = AccountInfoDouble(ACCOUNT_EQUITY) *
RiskPercent / 100.0;
if(budget <= 0.0)
return 0.0;
// Round down; never force the minimum lot above the risk budget.
double volume = MathMin(maximum, budget * minimum / (-loss));
volume = NormalizeDouble(MathFloor(volume / step) * step, 8);
if(volume < minimum)
return 0.0;
double margin = 0.0;
if(!OrderCalcMargin(type, _Symbol, volume, entry, margin) ||
margin > AccountInfoDouble(ACCOUNT_MARGIN_FREE))
return 0.0;
return volume;
}
void OnTick()
{
datetime bar = iTime(_Symbol, PERIOD_H1, 0);
if(bar == 0 || bar == lastBar)
return;
if(lastBar == 0)
{
lastBar = bar;
return;
}
if(BarsCalculated(fastHandle) < 52 ||
BarsCalculated(slowHandle) < 52)
return;
double fast[2], slow[2];
if(CopyBuffer(fastHandle, 0, 1, 2, fast) != 2 ||
CopyBuffer(slowHandle, 0, 1, 2, slow) != 2)
return;
lastBar = bar;
// Account-wide gate also avoids competing with pending orders.
if(PositionsTotal() > 0 || OrdersTotal() > 0)
return;
// CopyBuffer stores the older closed bar first: [0]=2, [1]=1.
bool buy = fast[0] <= slow[0] && fast[1] > slow[1];
bool sell = fast[0] >= slow[0] && fast[1] < slow[1];
if(!buy && !sell)
return;
MqlTick tick;
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(!SymbolInfoTick(_Symbol, tick) || tickSize <= 0.0 ||
tick.bid <= 0.0 || tick.ask <= 0.0)
return;
ENUM_ORDER_TYPE type = buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
double direction = buy ? 1.0 : -1.0;
double entry = buy ? tick.ask : tick.bid;
double stop = AlignPrice(
entry - direction * StopLossPoints * _Point, tickSize, !buy);
double target = AlignPrice(
entry + direction * TakeProfitPoints * _Point, tickSize, buy);
double reference = buy ? tick.bid : tick.ask;
double minimumDistance = MathMax(
_Point,
(double)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) *
_Point);
if(stop <= 0.0 || target <= 0.0 ||
direction * (reference - stop) < minimumDistance ||
direction * (target - reference) < minimumDistance)
{
Print("Signal skipped: SL/TP violate broker stop distances.");
return;
}
double volume = RiskVolume(type, entry, stop);
if(volume <= 0.0)
{
Print("Signal skipped: insufficient risk budget or margin.");
return;
}
bool sent = trade.PositionOpen(
_Symbol, type, volume, entry, stop, target, "EMA20/EMA50 H1");
uint result = trade.ResultRetcode();
if(!sent || (result != TRADE_RETCODE_DONE &&
result != TRADE_RETCODE_DONE_PARTIAL &&
result != TRADE_RETCODE_PLACED))
PrintFormat("Order failed (%u): %s",
result, trade.ResultRetcodeDescription());
}
MT4 indicator: trading sessions · mql4
Write a complete MQL4 indicator for MetaTrader 4 that colors the Asian, European and American trading sessions on the chart. Each session start and end is an input. Use English ASCII in all comments, labels and strings. Return exactly one full fenced mql4 source file. Compile-only example.
#property strict
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 0
// Example times only. Adjust them to your broker's server time.
// Times must use HH:MM. Equal start and end times are rejected.
// An end time earlier than its start time means an overnight session.
input string AsianStart = "00:00";
input string AsianEnd = "09:00";
input color AsianColor = clrLightSteelBlue;
input string EuropeanStart = "08:00";
input string EuropeanEnd = "17:00";
input color EuropeanColor = clrPaleGreen;
input string AmericanStart = "13:00";
input string AmericanEnd = "22:00";
input color AmericanColor = clrMistyRose;
// Previous calendar days to draw, with today included additionally.
input int LookbackDays = 10;
input int RefreshSeconds = 5;
struct SessionSpec
{
string title;
int startMinute;
int endMinute;
color fillColor;
};
SessionSpec g_sessions[3];
string g_prefix = "";
uint g_lastRefreshMs = 0;
bool g_hasRefreshed = false;
// Parse a strict, ASCII HH:MM value.
bool ParseHHMM(const string text, int &minutes)
{
if(StringLen(text) != 5)
return false;
if(StringGetCharacter(text, 2) != ':')
return false;
for(int i = 0; i < 5; i++)
{
if(i == 2)
continue;
ushort ch = StringGetCharacter(text, i);
if(ch < '0' || ch > '9')
return false;
}
int hour = (int)StringToInteger(StringSubstr(text, 0, 2));
int minute = (int)StringToInteger(StringSubstr(text, 3, 2));
if(hour > 23 || minute > 59)
return false;
minutes = hour * 60 + minute;
return true;
}
bool ConfigureSession(SessionSpec &session,
const string title,
const string startText,
const string endText,
const color fillColor)
{
session.title = title;
session.fillColor = fillColor;
if(!ParseHHMM(startText, session.startMinute) ||
!ParseHHMM(endText, session.endMinute))
{
Print("SessionColors: invalid ", title,
" time. Use HH:MM from 00:00 to 23:59.");
return false;
}
if(session.startMinute == session.endMinute)
{
Print("SessionColors: ", title,
" start and end times must differ.");
return false;
}
return true;
}
// Reserve a unique namespace so multiple instances do not interfere.
bool ReserveObjectPrefix()
{
string root = "SC_" +
IntegerToString((long)GetTickCount()) + "_";
for(int slot = 0; slot < 1000; slot++)
{
string candidate = root + IntegerToString(slot) + "_";
string marker = candidate + "Owner";
if(ObjectFind(0, marker) >= 0)
continue;
ResetLastError();
if(!ObjectCreate(0, marker, OBJ_LABEL, 0, 0, 0))
{
Print("SessionColors: cannot create instance marker. Error ",
GetLastError());
return false;
}
g_prefix = candidate;
ObjectSetString(0, marker, OBJPROP_TEXT, "");
ObjectSetInteger(0, marker, OBJPROP_COLOR, clrNONE);
ObjectSetInteger(0, marker, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, marker, OBJPROP_SELECTED, false);
ObjectSetInteger(0, marker, OBJPROP_HIDDEN, true);
return true;
}
Print("SessionColors: cannot reserve an object namespace.");
return false;
}
// Remove only objects owned by this indicator instance.
void CleanObjects(const bool removeAll,
const datetime oldestStart,
const datetime now)
{
if(g_prefix == "")
return;
for(int i = ObjectsTotal(0, 0, -1) - 1; i >= 0; i--)
{
string name = ObjectName(0, i, 0, -1);
if(StringFind(name, g_prefix, 0) != 0)
continue;
if(removeAll)
{
ObjectDelete(0, name);
continue;
}
if(ObjectGetInteger(0, name, OBJPROP_TYPE) != OBJ_RECTANGLE)
continue;
datetime left = (datetime)ObjectGetInteger(
0, name, OBJPROP_TIME, 0);
if(left < oldestStart || left > now)
ObjectDelete(0, name);
}
}
void DrawSession(const SessionSpec &session,
const datetime dayStart,
const datetime now)
{
datetime sessionStart = dayStart + session.startMinute * 60;
datetime sessionEnd = dayStart + session.endMinute * 60;
if(sessionEnd < sessionStart)
sessionEnd += 86400;
if(now <= sessionStart)
return;
// Active sessions extend only as far as the latest server time.
datetime right = sessionEnd;
if(right > now)
right = now;
if(right <= sessionStart)
return;
MqlRates bars[];
// The end is exclusive. Available M1 bars define the price range.
// Missing history can load asynchronously; later refreshes retry it.
int copied = CopyRates(_Symbol, PERIOD_M1,
sessionStart, right - 1, bars);
if(copied <= 0)
return;
bool found = false;
double highest = 0.0;
double lowest = 0.0;
for(int i = 0; i < copied; i++)
{
if(bars[i].time < sessionStart || bars[i].time >= right)
continue;
if(!found)
{
highest = bars[i].high;
lowest = bars[i].low;
found = true;
}
else
{
if(bars[i].high > highest)
highest = bars[i].high;
if(bars[i].low < lowest)
lowest = bars[i].low;
}
}
// Empty sessions, including closed-market periods, are not drawn.
if(!found)
return;
// Keep a flat, one-price session visible.
if(highest <= lowest)
{
double padding = _Point;
if(padding <= 0.0)
padding = 0.00000001;
highest += padding;
lowest -= padding;
}
string name = g_prefix + session.title + "_" +
IntegerToString((long)dayStart);
if(ObjectFind(0, name) < 0)
{
ResetLastError();
if(!ObjectCreate(0, name, OBJ_RECTANGLE, 0,
sessionStart, highest, right, lowest))
{
Print("SessionColors: cannot create rectangle. Error ",
GetLastError());
return;
}
ObjectSetInteger(0, name, OBJPROP_COLOR, session.fillColor);
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
ObjectSetInteger(0, name, OBJPROP_FILL, true);
ObjectSetInteger(0, name, OBJPROP_BACK, true);
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, name, OBJPROP_SELECTED, false);
ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, name, OBJPROP_TIMEFRAMES, OBJ_ALL_PERIODS);
ObjectSetString(0, name, OBJPROP_TOOLTIP,
session.title + " session (server time)");
}
ObjectMove(0, name, 0, sessionStart, highest);
ObjectMove(0, name, 1, right, lowest);
}
void RefreshSessions(const bool force)
{
if(g_prefix == "")
return;
uint tick = GetTickCount();
uint interval = (uint)(RefreshSeconds * 1000);
// Unsigned subtraction also handles GetTickCount rollover.
if(!force && g_hasRefreshed &&
(uint)(tick - g_lastRefreshMs) < interval)
return;
datetime now = TimeCurrent();
if(now <= 0)
return;
MqlDateTime parts;
if(!TimeToStruct(now, parts))
return;
parts.hour = 0;
parts.min = 0;
parts.sec = 0;
datetime today = StructToTime(parts);
if(today <= 0)
return;
g_lastRefreshMs = tick;
g_hasRefreshed = true;
datetime oldestStart = today - LookbackDays * 86400;
CleanObjects(false, oldestStart, now);
// Oldest sessions are created first. Filled boxes can overlap.
for(int dayOffset = LookbackDays; dayOffset >= 0; dayOffset--)
{
datetime dayStart = today - dayOffset * 86400;
for(int sessionIndex = 0; sessionIndex < 3; sessionIndex++)
DrawSession(g_sessions[sessionIndex], dayStart, now);
}
ChartRedraw(0);
}
int OnInit()
{
g_prefix = "";
g_hasRefreshed = false;
g_lastRefreshMs = 0;
if(LookbackDays < 1 || LookbackDays > 90)
{
Print("SessionColors: LookbackDays must be from 1 to 90.");
return INIT_PARAMETERS_INCORRECT;
}
if(RefreshSeconds < 1 || RefreshSeconds > 3600)
{
Print("SessionColors: RefreshSeconds must be from 1 to 3600.");
return INIT_PARAMETERS_INCORRECT;
}
if(!ConfigureSession(g_sessions[0], "Asian",
AsianStart, AsianEnd, AsianColor) ||
!ConfigureSession(g_sessions[1], "European",
EuropeanStart, EuropeanEnd, EuropeanColor) ||
!ConfigureSession(g_sessions[2], "American",
AmericanStart, AmericanEnd, AmericanColor))
return INIT_PARAMETERS_INCORRECT;
if(!ReserveObjectPrefix())
return INIT_FAILED;
ResetLastError();
if(!EventSetTimer(RefreshSeconds))
{
Print("SessionColors: cannot start refresh timer. Error ",
GetLastError());
CleanObjects(true, 0, 0);
g_prefix = "";
return INIT_FAILED;
}
IndicatorShortName("Session Colors (server time)");
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
EventKillTimer();
CleanObjects(true, 0, 0);
g_prefix = "";
ChartRedraw(0);
}
void OnTimer()
{
// Retry history requests even when the chart receives no new ticks.
RefreshSessions(true);
}
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
RefreshSessions(prev_calculated == 0);
return rates_total;
}
How to install the generated code
MetaTrader 4 and 5. Press F4 to open MetaEditor, create the appropriate source file, paste the code and compile with F7. Find the program in Navigator and attach it to a chart. Expert Advisors also require algorithmic trading to be enabled.
TradingView. Open the Pine Editor at the bottom of the chart, paste the code and click "Add to chart".
MQL4 programming guide · MQL5 programming for MetaTrader 5
Frequently asked questions
Do I need to know how to code?
No. Describe the required behaviour in plain language. Basic programming knowledge helps you review the generated result.
What is the best AI for MQL5 coding?
For MQL5 coding, platform-specific instructions and testing matter. Name the platform, provide compiler errors and refine the result in the same conversation.
How is an MT4 Expert Advisor different from an MT5 one?
MQL4 and MQL5 use different trading and indicator APIs. An MT4 EA needs rewriting for MT5; name the target platform in your request.
Can I convert MQL4 to MQL5?
Yes. Paste the source code and ask for an MT5 version. Always check the result in the Strategy Tester: trading functions behave differently in the two languages.
What if the code does not compile?
Copy the error text from MetaEditor or the Pine Editor and send it in the same conversation. The AI will suggest a fix.
Can the AI generate Pine Script for TradingView?
Yes. TradingView code is written in Pine Script, both indicators and strategies for the built-in tester.
Does an Expert Advisor guarantee profit?
No. Code implements your instructions; it does not establish profitability. Use the Strategy Tester and a demo account before risking real money.
Build your own Expert Advisor
Describe the idea and get code for MetaTrader or TradingView.
Sign up and generate codeAI-generated code can contain errors. Test it in the Strategy Tester and on a demo account. The service does not give trading advice and does not guarantee returns; trading decisions are yours.