This tutorial covers all the prompts and code used in the video tutorial for this ChatGPT MT5 EA. This is purely educational so be sure to learn, adapt and test the code before use. Many traders use EA’s to trade on CFD prop firm via a VPS which allows the EA to run 24/7 without your computer having to be on all day.
Prompt 1
Upload MQL5.pdf
Please read this entire mql5 pdf, master the concepts of coding in mql5 along with financial markets, risk management and trading strategies. You will write in mql5 to create expert advisors in this chat for the mt5 platform. Make the code professional and efficient, considering system resources when the code is running, given execution speed is critical. Please wait for directions as to the code I need you to write. For now, simply take in the mql5 knowledge to ensure you can write code at expert level.
Prompt 2
Please make an EA that buys the US30 symbol at the market open time (16:30) and looks for additional entry points when the market pulls back by its average true range for the day. It will build a position over time, bringing stops to break even once the current price is 1.5 times away from the current daily ATR. It will close all trades at a target balance that I input. Stops to be 1.2 of the ATR lower than the entry price. Ensure that we only move the stops to break even once per trade, we can have multiple trades running for this strategy but don’t allow it to send more than one trade at a time. Additionally, with consideration for prop firms, I would like there to be a failsafe stop, closing out all trades if the equity reduces by a percentage I input.
Prompt 3
After compiling the code, copy all of the errors (click the top one, then hold shift and click the bottom one and then CTRL C to copy). Then paste those errors directly into the ChatGPT chat.
Prompt 4
After compiling the next set of code, copy all of the errors (click the top one, then hold shift and click the bottom one and then CTRL C to copy). Then paste those errors directly into the ChatGPT chat.
Prompt 5
The same errors are still present. **Accidentally pasted the code in.
Prompt 6
Paste the errors in again
Prompt 7
Errors again
Write the full EA but please ensure there are no errors.
Prompt 8
still errors. ensure all the mqql5 is up to date please, maybe the refference pdf i gave you is a bit old
Prompt 9
These i’s are giving us some serious trouble, why is it an error and why aren’t you fixing it?
Prompt 10
Errors
Prompt 11
i set the encoding to ansi could you please make me the correct code as the same errors showed up after comiling
prompt 12
is it possible the set position index isn’t correct for mq5 files
prompt 13
please rewrite ensuring it is for mq5
prompt 14
These errors seem like a very simple fix, please have a deep thought about why they aren’t working and figure out a solution to get it working.
Prompt 15
This code works great, can you change the target from equity to a percentage with an input of 10%
Prompt 16
Can you now make this code as efficient as possible, taking into consideration system resources, latency and MT5 platform limits.
ChatGPT MT5 EA Code from the Video
property strict
property version “2.1”
property description “US30 ATR Position Builder (Netting-only, 10% target). Buys at 16:30, adds on ATR pullback, BE at 1.5×ATR, SL=1.2×ATR, closes at %-gain or DD failsafe.”
include
//============== Inputs ==============
input string InpSymbol = “US30”; // Broker symbol
input double InpLots = 0.10; // Lot size
input int InpATRPeriod = 14; // ATR period (Daily)
input double InpSL_ATR_Mult = 1.2; // Initial SL multiple
input double InpBE_ATR_Mult = 1.5; // BE move multiple
input int InpSessHour = 16; // Market open hour
input int InpSessMinute = 30; // Market open minute
input bool InpTradeMon = true;
input bool InpTradeTue = true;
input bool InpTradeWed = true;
input bool InpTradeThu = true;
input bool InpTradeFri = true;
input bool InpAllowAdds = true;
input int InpMinSecondsBetweenOrders= 5;
input ulong InpMagic = 73015001;
input double InpEquityTarget = 10.0; // % target gain (0 disables)
input double InpMaxDDPercent = 8.0; // % max drawdown failsafe
input bool InpOneSessionPerDay = true;
//============== Internals ============
CTrade trade;
int atr_handle = INVALID_HANDLE;
double atr_val = 0.0;
datetime last_order_time = 0;
MqlTick last_tick;
double session_high = 0.0;
double last_trade_session_high = 0.0;
int sess_y=0, sess_m=0, sess_d=0;
bool placed_open_trade_today = false;
double peak_equity = 0.0;
//============== Utilities =============
bool IsTradingDay(int wday)
{
bool days[7] = {false, InpTradeMon, InpTradeTue, InpTradeWed, InpTradeThu, InpTradeFri, false};
return (wday>=0 && wday<=6)?days[wday]:false;
}
bool CooldownPassed() { return (TimeCurrent()-last_order_time)>=InpMinSecondsBetweenOrders; }
bool RefreshATR()
{
if(atr_handle==INVALID_HANDLE) return false;
double buf[];
if(CopyBuffer(atr_handle,0,0,1,buf)<1) return false; atr_val=buf[0]; return (atr_val>0.0);
}
bool WithinSession(datetime t)
{
MqlDateTime mt; TimeToStruct(t,mt);
return (mt.hour==InpSessHour && mt.min==InpSessMinute);
}
bool IsNewDay(datetime t,int &y,int &m,int &d)
{
MqlDateTime mt; TimeToStruct(t,mt);
if(mt.year!=y||mt.mon!=m||mt.day!=d){ y=mt.year; m=mt.mon; d=mt.day; return true; }
return false;
}
bool GetSymbolProps(string sym,double &minlot,double &step,long &stoplvl,double &pt)
{
return SymbolInfoDouble(sym,SYMBOL_VOLUME_MIN,minlot)
&& SymbolInfoDouble(sym,SYMBOL_VOLUME_STEP,step)
&& SymbolInfoInteger(sym,SYMBOL_TRADE_STOPS_LEVEL,stoplvl)
&& SymbolInfoDouble(sym,SYMBOL_POINT,pt);
}
double NormalizeLot(string sym,double lot)
{
double minlot,step,pt; long stoplvl;
if(!GetSymbolProps(sym,minlot,step,stoplvl,pt)) return lot;
int digs=(int)MathMax(0,-MathRound(MathLog10(step)));
double fl=MathFloor(lot/step)*step;
return NormalizeDouble(MathMax(minlot,fl),digs);
}
//============== Core helpers ===========
void UpdatePeakEquity()
{
double eq=AccountInfoDouble(ACCOUNT_EQUITY);
if(eq>peak_equity) peak_equity=eq;
}
bool SessionReady()
{
datetime now=TimeCurrent();
if(IsNewDay(now,sess_y,sess_m,sess_d))
{
placed_open_trade_today=false;
session_high=0.0;
last_trade_session_high=0.0;
peak_equity=AccountInfoDouble(ACCOUNT_EQUITY);
}
MqlDateTime mt; TimeToStruct(now,mt);
if(!IsTradingDay(mt.day_of_week)) return false;
if(InpOneSessionPerDay && placed_open_trade_today) return false;
return WithinSession(now);
}
void UpdateSessionHigh(string sym)
{
if(!SymbolInfoTick(sym,last_tick)) return;
if(session_high==0.0 || last_tick.bid>session_high)
session_high=last_tick.bid;
}
bool CanAdd(string sym,double atr)
{
if(!InpAllowAdds||session_high<=0.0) return false; if(!SymbolInfoTick(sym,last_tick)) return false; if(session_high<=last_trade_session_high) return false; double pullback=session_high-last_tick.bid; return (pullback>=atr && CooldownPassed());
}
//============== Trading ================
bool SendBuy(string sym,double lot,double sl)
{
if(!CooldownPassed()) return false;
trade.SetExpertMagicNumber(InpMagic);
trade.SetAsyncMode(false);
ResetLastError();
bool ok=trade.Buy(lot,sym,0.0,sl,0.0,”US30_ATR_Builder”);
if(ok) last_order_time=TimeCurrent();
else Print(“Buy failed, err=”,_LastError);
return ok;
}
void CloseAllForSymbol_Netting(string sym)
{
trade.SetExpertMagicNumber(InpMagic);
int guard=0;
while(PositionSelect(sym) && guard<10)
{
if(!trade.PositionClose(sym))
{
Print(“Close failed, err=”,_LastError);
Sleep(100);
}
else Sleep(100);
guard++;
}
}
void ManageBE_Netting(string sym,double atr)
{
if(!PositionSelect(sym)) return;
if((ulong)PositionGetInteger(POSITION_MAGIC)!=InpMagic) return;
if((long)PositionGetInteger(POSITION_TYPE)!=POSITION_TYPE_BUY) return;
double entry=PositionGetDouble(POSITION_PRICE_OPEN);
double sl =PositionGetDouble(POSITION_SL);
double bid =SymbolInfoDouble(sym,SYMBOL_BID);
if(bid-entry>=InpBE_ATR_Multatr && slpt,0.0);
}
}
void TryOpenInitial(string sym,double atr)
{
if(!SessionReady()) return;
if(!SymbolInfoTick(sym,last_tick)) return;
double minlot,step,pt; long stoplvl;
if(!GetSymbolProps(sym,minlot,step,stoplvl,pt)) return;
double lot=NormalizeLot(sym,InpLots);
double sl =last_tick.bid-InpSL_ATR_Multatr; double mindist=(double)stoplvlpt;
if(last_tick.bid-sl<mindist) sl=last_tick.bid-mindist;
if(SendBuy(sym,lot,sl))
{
placed_open_trade_today=true;
last_trade_session_high=session_high;
}
}
void TryAddOnPullback(string sym,double atr)
{
if(!SymbolInfoTick(sym,last_tick)) return;
double minlot,step,pt; long stoplvl;
if(!GetSymbolProps(sym,minlot,step,stoplvl,pt)) return;
double lot=NormalizeLot(sym,InpLots);
double sl =last_tick.bid-InpSL_ATR_Multatr; double mindist=(double)stoplvlpt;
if(last_tick.bid-sl<mindist) sl=last_tick.bid-mindist;
if(SendBuy(sym,lot,sl))
last_trade_session_high=session_high;
}
//============== Equity control ==========
void EquityControls(string sym)
{
UpdatePeakEquity();
double eq = AccountInfoDouble(ACCOUNT_EQUITY);
double start_eq = AccountInfoDouble(ACCOUNT_BALANCE);
double target_eq = start_eq * (1.0 + InpEquityTarget / 100.0);
//— take profit at % gain
if(InpEquityTarget>0.0 && eq>=target_eq)
{
Print(“Target +”,DoubleToString(InpEquityTarget,2),
“% reached (Equity “,DoubleToString(eq,2),”). Closing all.”);
CloseAllForSymbol_Netting(sym);
return;
}
//— drawdown failsafe
if(InpMaxDDPercent>0.0 && peak_equity>0.0)
{
double thr = peak_equity * (1.0 – InpMaxDDPercent / 100.0);
if(eq <= thr)
{
Print(“Drawdown “,DoubleToString(InpMaxDDPercent,2),
“% hit. Closing all positions.”);
CloseAllForSymbol_Netting(sym);
}
}
Comment(“Equity: “,DoubleToString(eq,2),
” | Start: “,DoubleToString(start_eq,2),
” | Target: “,DoubleToString(target_eq,2),
” | Peak: “,DoubleToString(peak_equity,2));
}
//============== Events =================
int OnInit()
{
string sym=(InpSymbol==””?_Symbol:InpSymbol);
if(!SymbolSelect(sym,true)){ Print(“SymbolSelect failed for “,sym); return INIT_FAILED; }
atr_handle=iATR(sym,PERIOD_D1,InpATRPeriod);
if(atr_handle==INVALID_HANDLE){ Print(“Failed to create ATR handle.”); return INIT_FAILED; }
datetime now=TimeCurrent(); MqlDateTime mt; TimeToStruct(now,mt);
sess_y=mt.year; sess_m=mt.mon; sess_d=mt.day;
peak_equity=AccountInfoDouble(ACCOUNT_EQUITY);
trade.SetExpertMagicNumber(InpMagic);
trade.SetAsyncMode(false);
Print(“US30_ATR_PositionBuilder_PercentTarget initialized.”);
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
if(atr_handle!=INVALID_HANDLE) IndicatorRelease(atr_handle);
Print(“EA deinitialized.”);
Comment(“”);
}
void OnTick()
{
string sym=(InpSymbol==””?_Symbol:InpSymbol);
if(!SymbolInfoTick(sym,last_tick)) return;
EquityControls(sym);
if(!RefreshATR()) return;
UpdateSessionHigh(sym);
ManageBE_Netting(sym,atr_val);
if(!CooldownPassed()) return;
TryOpenInitial(sym,atr_val);
if(InpAllowAdds && CanAdd(sym,atr_val))
TryAddOnPullback(sym,atr_val);
}