Please help with MQL5 code for EA which opens a trade automatically once an existing trade is closed.
Please help with MQL5 code for EA which opens a trade automatically once an existing trade is closed.
If you want some code, search the CodeBase. Otherwise, if you want a proper answer, tell us what you have done so far and we can guide you through the correct path.
input double lotSize = 0.01; // Lot size for trades input int slippage = 3; // Slippage allowance input double stopLoss = 50.0; // Stop loss in points input double takeProfit = 100.0; // Take profit in points input bool openBuyTrade = true; // Open buy trade if true, else sell ulong lastTradeTicket = 0; // Ticket of the last trade //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { // Immediately open an initial trade when the EA starts OpenTrade(openBuyTrade); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // Check if the last trade is still open if(PositionSelectByTicket(lastTradeTicket)) { // Last trade is still open, no action needed return; } else { // If the last trade is not open (closed), open a new trade OpenTrade(openBuyTrade); } } //+------------------------------------------------------------------+ //| Function to open a trade | //+------------------------------------------------------------------+ void OpenTrade(bool buy) { double price = buy ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID); double sl = buy ? price - stopLoss * _Point : price + stopLoss * _Point; double tp = buy ? price + takeProfit * _Point : price - takeProfit * _Point; MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); request.action = TRADE_ACTION_DEAL; request.symbol = _Symbol; request.volume = lotSize; request.type = buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL; request.price = price; request.sl = sl; request.tp = tp; request.deviation = slippage; request.magic = 0; // Adjust if using multiple EAs request.comment = "TradeOpenerEA Trade"; if(!OrderSend(request, result)) { Print("Trade Error: ", GetLastError()); } else { lastTradeTicket = result.deal; } } //+------------------------------------------------------------------+

You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register