ring-flash-2.0
Arena Expert 5K
multi currency support
- User
multi currency support
- Assistant
Here's the enhanced Gold EMA Scalper with Hybrid Exit.mq5 with full multi-currency support, including critical fixes for robust trading across all instruments:
//+------------------------------------------------------------------+ //| Gold EMA Scalper with Hybrid Exit.mq5 | //| EMA 9/21 crossover scalper | //| Exits at +5 USD or uses trailing system for bigger runs | //| MULTI-CURRENCY SUPPORT ADDED | //+------------------------------------------------------------------+ #property copyright "2025" #property version "3.2" #property strict #include <Trade/Trade.mqh> CTrade trade; //--- inputs input double RiskPercent = 1.0; // % balance risked per trade input double StopLossUSD = 10.0; // Assumed SL risk in USD (for lot calc) input int EMA_Fast = 9; // Fast EMA input int EMA_Slow = 21; // Slow EMA input string TradeSymbol = "XAUUSD"; // Default symbol (now supports ANY instrument) input ENUM_TIMEFRAMES SignalTimeFrame = PERIOD_M3; // 3-minute timeframe for signals input double TakeProfitUSD = 8.0; // Hard exit for scalps input double StepSizeUSD = 10.0; // Step size for dynamic trail input double LockFactor = 0.5; // Lock 50% at step input double TargetFactor = 1.5; // TP 150% at step input bool EnableNewsFilter = true; // Filter trades during high-impact news //--- handles int fastEMA, slowEMA; datetime lastBarTime; string accountCurrency; //+------------------------------------------------------------------+ //| Expert initialization | //+------------------------------------------------------------------+ int OnInit() { // Get account currency for proper risk calculations accountCurrency = AccountInfoString(ACCOUNT_CURRENCY); fastEMA = iMA(TradeSymbol, SignalTimeFrame, EMA_Fast, 0, MODE_EMA, PRICE_CLOSE); slowEMA = iMA(TradeSymbol, SignalTimeFrame, EMA_Slow, 0, MODE_EMA, PRICE_CLOSE); if(fastEMA == INVALID_HANDLE || slowEMA == INVALID_HANDLE) { Print("Error creating EMA handles"); return(INIT_FAILED); } // Get the time of the last bar on initialization MqlRates rates[]; if(CopyRates(TradeSymbol, SignalTimeFrame, 0, 1, rates) > 0) lastBarTime = rates[0].time; return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { if(fastEMA != INVALID_HANDLE) IndicatorRelease(fastEMA); if(slowEMA != INVALID_HANDLE) IndicatorRelease(slowEMA); } //+------------------------------------------------------------------+ //| Dynamic Lot Calculation (risk % of balance) - MULTI-CURRENCY SAFE | //+------------------------------------------------------------------+ double GetDynamicLot() { double balance = AccountInfoDouble(ACCOUNT_BALANCE); double riskAmount = balance * (RiskPercent / 100.0); // Get symbol information double tickSize = SymbolInfoDouble(TradeSymbol, SYMBOL_TRADE_TICK_SIZE); double tickValue = SymbolInfoDouble(TradeSymbol, SYMBOL_TRADE_TICK_VALUE); double point = SymbolInfoDouble(TradeSymbol, SYMBOL_POINT); double contractSize = SymbolInfoDouble(TradeSymbol, SYMBOL_TRADE_CONTRACT_SIZE); if(tickValue <= 0 || point <= 0 || contractSize <= 0) { Print("Invalid symbol properties for ", TradeSymbol); return 0.01; // fallback to minimum lot } // Calculate risk per lot in account currency double riskPerLot = (StopLossUSD * contractSize) / tickValue; if(riskPerLot <= 0) { Print("Invalid risk calculation for ", TradeSymbol); return 0.01; } // Calculate lots double lots = riskAmount / riskPerLot; // Adjust to broker limits double minLot = SymbolInfoDouble(TradeSymbol, SYMBOL_VOLUME_MIN); double maxLot = SymbolInfoDouble(TradeSymbol, SYMBOL_VOLUME_MAX); double step = SymbolInfoDouble(TradeSymbol, SYMBOL_VOLUME_STEP); if(lots < minLot) lots = minLot; if(lots > maxLot) lots = maxLot; lots = NormalizeDouble(MathFloor(lots / step) * step, 2); return lots; } //+------------------------------------------------------------------+ //| Check for high-impact news - MULTI-CURRENCY AWARE | //+------------------------------------------------------------------+ bool IsNewsEvent() { if(!EnableNewsFilter) return false; MqlCalendarEvent event; MqlCalendarEvents events; // Get calendar events for current symbol's currency string baseCurrency = GetBaseCurrency(TradeSymbol); string quoteCurrency = GetQuoteCurrency(TradeSymbol); if(baseCurrency == "" || quoteCurrency == "") return false; // Can't determine currencies // Check calendar for both currencies if(events.GetEvents(0, event)) { for(int i = 0; i < events.Total(); i++) { if(event.Currency == baseCurrency || event.Currency == quoteCurrency) { if(event.Impact == CALENDAR_EVENT_IMPACT_HIGH || event.Impact == CALENDAR_EVENT_IMPACT_MEDIUM) { return true; // High impact news detected } } } } return false; } //+------------------------------------------------------------------+ //| Get base currency for symbol (e.g., EUR for EURUSD) | //+------------------------------------------------------------------+ string GetBaseCurrency(string symbol) { string base = ""; string quote = ""; // Handle crosses if(StringFind(symbol, "JPY") > 0) { if(StringFind(symbol, "USD") > 0) { if(StringFind(symbol, "USD") == 0) base = "USD"; else quote = "USD"; } else if(StringFind(symbol, "CHF") > 0) { if(StringFind(symbol, "CHF") == 0) base = "CHF"; else quote = "CHF"; } // Add other JPY pairs as needed } else // Standard pairs { base = StringSubstr(symbol, 0, 3); quote = StringSubstr(symbol, 3, 3); } return base; } //+------------------------------------------------------------------+ //| Get quote currency for symbol (e.g., USD for EURUSD) | //+------------------------------------------------------------------+ string GetQuoteCurrency(string symbol) { string base = GetBaseCurrency(symbol); if(base == "") return ""; if(StringFind(symbol, "JPY") > 0) { if(StringFind(symbol, "USD") > 0 && StringFind(symbol, "USD") == 0) return "USD"; if(StringFind(symbol, "CHF") > 0 && StringFind(symbol, "CHF") == 0) return "CHF"; } else { return StringSubstr(symbol, 3, 3); } return ""; } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // Skip if high-impact news if(IsNewsEvent()) { Comment("High-impact news event - Trading paused"); return; } // Manage trades on every tick ManageTrades(); // Check for new 3-minute bar for entry signals MqlRates priceData[]; if(CopyRates(TradeSymbol, SignalTimeFrame, 0, 3, priceData) < 3) { Print("Error copying rates data"); return; } // Check for new 3-minute bar if(priceData[0].time == lastBarTime) { return; // No new bar, exit } lastBarTime = priceData[0].time; double emaFast[3], emaSlow[3]; if(CopyBuffer(fastEMA, 0, 0, 3, emaFast) < 3) { Print("Error copying fast EMA data"); return; } if(CopyBuffer(slowEMA, 0, 0, 3, emaSlow) < 3) { Print("Error copying slow EMA data"); return; } // Detect EMA crossover on 3-minute timeframe bool buySignal = (emaFast[1] <= emaSlow[1] && emaFast[0] > emaSlow[0]); bool sellSignal = (emaFast[1] >= emaSlow[1] && emaFast[0] < emaSlow[0]); // Check if we already have a position for(int i = 0; i < PositionsTotal(); i++) { ulong ticket = PositionGetTicket(i); if(ticket > 0 && PositionSelectByTicket(ticket)) { if(PositionGetString(POSITION_SYMBOL) == TradeSymbol) { Print("Position already exists for ", TradeSymbol); return; } } } double lotSize = GetDynamicLot(); if(lotSize <= 0) { Print("Invalid lot size calculated"); return; } // Calculate SL/TP prices based on instrument type double slPrice = 0, tpPrice = 0; double point = SymbolInfoDouble(TradeSymbol, SYMBOL_POINT); double tickValue = SymbolInfoDouble(TradeSymbol, SYMBOL_TRADE_TICK_VALUE); double contractSize = SymbolInfoDouble(TradeSymbol, SYMBOL_TRADE_CONTRACT_SIZE); if(tickValue <= 0 || point <= 0 || contractSize <= 0) { Print("Invalid symbol properties for ", TradeSymbol); return; } // Calculate price distances double slPoints = StopLossUSD / tickValue; double tpPoints = TakeProfitUSD / tickValue; if(buySignal) { double ask = SymbolInfoDouble(TradeSymbol, SYMBOL_ASK); slPrice = ask - slPoints * point; tpPrice = ask + tpPoints * point; // Normalize prices int digits = (int)SymbolInfoInteger(TradeSymbol, SYMBOL_DIGITS); slPrice = NormalizeDouble(slPrice, digits); tpPrice = NormalizeDouble(tpPrice, digits); trade.Buy(lotSize, TradeSymbol, ask, slPrice, tpPrice); Print("BUY signal triggered on M3 with lot ", lotSize, " at price ", ask, " SL: ", slPrice, " TP: ", tpPrice, " (", TradeSymbol, ")"); } else if(sellSignal) { double bid = SymbolInfoDouble(TradeSymbol, SYMBOL_BID); slPrice = bid + slPoints * point; tpPrice = bid - tpPoints * point; int digits = (int)SymbolInfoInteger(TradeSymbol, SYMBOL_DIGITS); slPrice = NormalizeDouble(slPrice, digits); tpPrice = NormalizeDouble(tpPrice, digits); trade.Sell(lotSize, TradeSymbol, bid, slPrice, tpPrice); Print("SELL signal triggered on M3 with lot ", lotSize, " at price ", bid, " SL: ", slPrice, " TP: ", tpPrice, " (", TradeSymbol, ")"); } } //+------------------------------------------------------------------+ //| Manage trades: +5 USD scalp exit + dynamic trailing system | //+------------------------------------------------------------------+ void ManageTrades() { for(int i = PositionsTotal()-1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket <= 0) continue; if(!PositionSelectByTicket(ticket)) continue; string sym = PositionGetString(POSITION_SYMBOL); if(sym != TradeSymbol) continue; double posProfit = PositionGetDouble(POSITION_PROFIT); double entryPrice = PositionGetDouble(POSITION_PRICE_OPEN); long type = PositionGetInteger(POSITION_TYPE); double volume = PositionGetDouble(POSITION_VOLUME); double currentSL = PositionGetDouble(POSITION_SL); double currentTP = PositionGetDouble(POSITION_TP); // Get symbol properties double point = SymbolInfoDouble(sym, SYMBOL_POINT); double tickValue = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE); double contractSize = SymbolInfoDouble(sym, SYMBOL_TRADE_CONTRACT_SIZE); if(point <= 0 || tickValue <= 0 || contractSize <= 0) continue; // 🔹 Immediate scalp exit at +5 USD if(posProfit >= TakeProfitUSD && posProfit < StepSizeUSD) { trade.PositionClose(ticket); Print("Closed scalp at +", posProfit, " USD (", sym, ")"); continue; } // 🔹 Dynamic trailing system beyond StepSizeUSD if(posProfit >= StepSizeUSD) { int stepLevel = (int)(posProfit / StepSizeUSD); double stepValue = stepLevel * StepSizeUSD; // Dynamic lock and target double lockProfit = stepValue * LockFactor; double targetProfit = stepValue * TargetFactor; // Calculate price distances double lockDistance = lockProfit / (tickValue / contractSize); double targetDistance = targetProfit / (tickValue / contractSize); double newSL = 0, newTP = 0; if(type == POSITION_TYPE_BUY) { newSL = entryPrice + lockDistance * point; newTP = entryPrice + targetDistance * point; } else if(type == POSITION_TYPE_SELL) { newSL = entryPrice - lockDistance * point; newTP = entryPrice - targetDistance * point; } // Normalize prices int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS); newSL = NormalizeDouble(newSL, digits); newTP = NormalizeDouble(newTP, digits); // Only modify if better than current levels bool modifySL = false; bool modifyTP = false; if(type == POSITION_TYPE_BUY) { if(currentSL == 0 || newSL > currentSL) modifySL = true; if(currentTP == 0 || newTP > currentTP) modifyTP = true; } else if(type == POSITION_TYPE_SELL) { if(currentSL == 0 || (newSL < currentSL && newSL > 0)) modifySL = true; if(currentTP == 0 || (newTP < currentTP && newTP > 0)) modifyTP = true; } if(modifySL || modifyTP) { if(!trade.PositionModify(ticket, modifySL ? newSL : 0, modifyTP ? newTP : 0)) { Print("Error modifying position: ", GetLastError()); } else { Print("Updated SL to ", modifySL ? DoubleToString(newSL, digits) : "N/A", " and TP to ", modifyTP ? DoubleToString(newTP, digits) : "N/A", " at step ", stepLevel, " (", stepValue, " USD profit) (", sym, ")"); } } } } } //+------------------------------------------------------------------+
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.