//+------------------------------------------------------------------+ //| MA50_Cross_EA.mq5 | //| Moving-average cross Expert Advisor | //| - money based SL / TP1 / TP2 / TP3 (separate for BUY and SELL) | //| - partial closes at TP1 and TP2 | //| - break-even lock and money trailing stop | //| - stage + original volume kept in terminal GlobalVariables | //| Works on hedging and netting accounts. | //+------------------------------------------------------------------+ #property copyright "MA50_Cross_EA" #property version "1.00" #property description "MA cross EA with dollar SL/TP, three targets, partial closes, break-even lock and dollar trailing." #include //+------------------------------------------------------------------+ //| Enumerations | //+------------------------------------------------------------------+ enum ENUM_OPPOSITE_MODE { OPPOSITE_IGNORE = 0, // Ignore opposite signal OPPOSITE_CLOSE_AND_OPEN = 1 // Close opposite positions, then open }; //+------------------------------------------------------------------+ //| Inputs | //+------------------------------------------------------------------+ input group "=== Moving Average ===" input int InpMAPeriod = 50; // MA period input ENUM_MA_METHOD InpMAMethod = MODE_SMA; // MA method input ENUM_APPLIED_PRICE InpMAPrice = PRICE_CLOSE; // MA applied price input bool InpLive = false; // Live bar signals (false = confirm on bar close) input group "=== Trading ===" input double InpLots = 0.10; // Lot size input long InpMagic = 505050; // Magic number input string InpComment = "MA50_Cross"; // Order comment input bool InpAllowBuy = true; // Allow BUY input bool InpAllowSell = true; // Allow SELL input int InpMaxPositions = 1; // Max positions (this symbol + magic) input ENUM_OPPOSITE_MODE InpReverseMode = OPPOSITE_CLOSE_AND_OPEN; // Opposite signal mode input int InpMaxSpread = 0; // Max spread in points (0 = off) input int InpSlippage = 30; // Slippage / deviation in points input group "=== Trading hours (server time) ===" input bool InpUseHours = false; // Use trading hours filter input int InpStartHour = 7; // Start hour 0-23 input int InpEndHour = 21; // End hour 0-23 (overnight supported) input group "=== BUY money targets (deposit currency, for the lot size above) ===" input double InpBuySL = 20.0; // BUY stop loss in money (0 = off) input double InpBuyTP1 = 10.0; // BUY target 1 in money (0 = off) input double InpBuyTP2 = 20.0; // BUY target 2 in money (0 = off) input double InpBuyTP3 = 40.0; // BUY target 3 in money (final TP, 0 = off) input group "=== SELL money targets (deposit currency, for the lot size above) ===" input double InpSellSL = 20.0; // SELL stop loss in money (0 = off) input double InpSellTP1 = 10.0; // SELL target 1 in money (0 = off) input double InpSellTP2 = 20.0; // SELL target 2 in money (0 = off) input double InpSellTP3 = 40.0; // SELL target 3 in money (final TP, 0 = off) input group "=== Partial close ===" input bool InpUsePartial = true; // Enable partial closes input double InpPartial1Pct = 50.0; // Percent of original lots closed at TP1 input double InpPartial2Pct = 25.0; // Percent of original lots closed at TP2 input group "=== Secure profit: break-even lock ===" input bool InpUseBreakEven = true; // Enable break-even lock input double InpBETrigger = 8.0; // Floating profit trigger in money input double InpBELock = 2.0; // Money profit locked by the new SL input group "=== Secure profit: money trailing ===" input bool InpUseTrailing = true; // Enable money trailing stop input double InpTrailStart = 15.0; // Start trailing at this floating profit input double InpTrailDist = 8.0; // Trail distance in money input double InpTrailStep = 2.0; // Minimum trailing step in money input group "=== Stage stop-loss moves ===" input double InpLockAfterTP1 = 2.0; // After TP1: money profit locked above entry //+------------------------------------------------------------------+ //| Globals | //+------------------------------------------------------------------+ CTrade trade; int g_maHandle = INVALID_HANDLE; int g_digits = 0; double g_point = 0.0; double g_volStep = 0.0; double g_volMin = 0.0; double g_volMax = 0.0; int g_volDigits = 2; datetime g_lastBar = 0; datetime g_lastSignalBar = 0; //+------------------------------------------------------------------+ //| Expert initialization | //+------------------------------------------------------------------+ int OnInit() { if(InpMAPeriod<1) { Print("Init error: MA period must be 1 or greater."); return(INIT_PARAMETERS_INCORRECT); } if(InpLots<=0.0) { Print("Init error: lot size must be greater than zero."); return(INIT_PARAMETERS_INCORRECT); } if(InpStartHour<0 || InpStartHour>23 || InpEndHour<0 || InpEndHour>23) { Print("Init error: trading hours must be between 0 and 23."); return(INIT_PARAMETERS_INCORRECT); } if(InpPartial1Pct<0.0 || InpPartial1Pct>100.0 || InpPartial2Pct<0.0 || InpPartial2Pct>100.0) { Print("Init error: partial close percentages must be between 0 and 100."); return(INIT_PARAMETERS_INCORRECT); } g_digits = (int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS); g_point = SymbolInfoDouble(_Symbol,SYMBOL_POINT); g_volStep = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP); g_volMin = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN); g_volMax = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX); if(g_point<=0.0) g_point = 1.0/MathPow(10.0,(double)g_digits); if(g_volStep<=0.0) g_volStep = 0.01; if(g_volMin<=0.0) g_volMin = g_volStep; if(g_volMax<=0.0) g_volMax = 100.0; g_volDigits = 0; double step = g_volStep; while(step<1.0 && g_volDigits<8) { step *= 10.0; g_volDigits++; } g_maHandle = iMA(_Symbol,_Period,InpMAPeriod,0,InpMAMethod,InpMAPrice); if(g_maHandle==INVALID_HANDLE) { Print("Init error: iMA handle could not be created. Error ",(string)GetLastError()); return(INIT_FAILED); } trade.SetExpertMagicNumber((ulong)InpMagic); trade.SetDeviationInPoints((ulong)MathMax(0,InpSlippage)); trade.SetTypeFillingBySymbol(_Symbol); trade.SetMarginMode(); trade.LogLevel(LOG_LEVEL_ERRORS); g_lastBar = (datetime)SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE); g_lastSignalBar = 0; Print("MA50_Cross_EA started on ",_Symbol," ",EnumToString((ENUM_TIMEFRAMES)_Period), " magic=",(string)InpMagic," lots=",DoubleToString(InpLots,g_volDigits)); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { if(g_maHandle!=INVALID_HANDLE) { IndicatorRelease(g_maHandle); g_maHandle = INVALID_HANDLE; } Print("MA50_Cross_EA stopped. Reason code ",(string)reason); } //+------------------------------------------------------------------+ //| Global variable helpers (stage + original volume per ticket) | //+------------------------------------------------------------------+ string GVPrefix() { return("MA50EA_"+IntegerToString(InpMagic)+"_"); } string GVName(const ulong ticket,const string suffix) { return(GVPrefix()+IntegerToString((long)ticket)+"_"+suffix); } int PositionStage(const ulong ticket) { string name = GVName(ticket,"stage"); if(!GlobalVariableCheck(name)) return(0); return((int)GlobalVariableGet(name)); } void SetPositionStage(const ulong ticket,const int stage) { GlobalVariableSet(GVName(ticket,"stage"),(double)stage); } double OriginalVolume(const ulong ticket,const double currentVolume) { string name = GVName(ticket,"vol"); if(!GlobalVariableCheck(name)) { GlobalVariableSet(name,currentVolume); return(currentVolume); } double stored = GlobalVariableGet(name); if(stored<=0.0) { GlobalVariableSet(name,currentVolume); return(currentVolume); } return(stored); } void CleanupGlobals() { string prefix = GVPrefix(); int total = GlobalVariablesTotal(); for(int i=total-1; i>=0; i--) { string name = GlobalVariableName(i); if(StringFind(name,prefix)!=0) continue; string rest = StringSubstr(name,StringLen(prefix)); int sep = StringFind(rest,"_"); if(sep<=0) continue; ulong ticket = (ulong)StringToInteger(StringSubstr(rest,0,sep)); if(ticket==0 || !PositionSelectByTicket(ticket)) GlobalVariableDel(name); } } //+------------------------------------------------------------------+ //| Money / volume helpers | //+------------------------------------------------------------------+ double MoneyToPrice(const double money,const double volume) { if(money<=0.0 || volume<=0.0) return(0.0); double tickValue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE); double tickSize = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE); if(tickValue<=0.0 || tickSize<=0.0) return(0.0); double moneyPerPrice = (tickValue/tickSize)*volume; if(moneyPerPrice<=0.0) return(0.0); return(money/moneyPerPrice); } double NormalizeLots(const double volume) { if(g_volStep<=0.0) return(0.0); double v = MathFloor(volume/g_volStep+0.5)*g_volStep; v = NormalizeDouble(v,g_volDigits); if(vg_volMax) v = g_volMax; return(NormalizeDouble(v,g_volDigits)); } double FloorLots(const double volume) { if(g_volStep<=0.0 || volume<=0.0) return(0.0); double v = MathFloor(volume/g_volStep+0.0000001)*g_volStep; return(NormalizeDouble(v,g_volDigits)); } //+------------------------------------------------------------------+ //| Market filters | //+------------------------------------------------------------------+ bool TimeAllowed() { if(!InpUseHours) return(true); MqlDateTime dt; if(!TimeToStruct(TimeCurrent(),dt)) return(false); int hour = dt.hour; if(InpStartHour==InpEndHour) return(true); if(InpStartHour=InpStartHour && hour=InpStartHour || hour0.0 && (bid-currentSL)0.0 && (currentTP-bid)0.0 && (currentSL-ask)0.0 && (ask-currentTP)0.0 && sl>(bid-minDist)) sl = bid-minDist; if(tp>0.0 && tp<(ask+minDist)) tp = ask+minDist; } else { if(sl>0.0 && sl<(ask+minDist)) sl = ask+minDist; if(tp>0.0 && tp>(bid-minDist)) tp = bid-minDist; } if(sl<0.0) sl = 0.0; if(tp<0.0) tp = 0.0; if(sl>0.0) sl = NormalizeDouble(sl,g_digits); if(tp>0.0) tp = NormalizeDouble(tp,g_digits); } //+------------------------------------------------------------------+ //| Signal | //+------------------------------------------------------------------+ bool GetSignal(int &direction) { direction = 0; int shift = (InpLive ? 0 : 1); int needed = shift+2; double ma[]; double close[]; ArraySetAsSeries(ma,true); ArraySetAsSeries(close,true); int copiedMA = CopyBuffer(g_maHandle,0,0,needed,ma); int copiedClose = CopyClose(_Symbol,_Period,0,needed,close); if(copiedMAmaSignal) { direction = 1; return(true); } if(cPrevious>=maPrevious && cSignal=0; i--) { ulong ticket = PositionGetTicket(i); if(ticket==0) continue; if(!PositionSelectByTicket(ticket)) continue; if(PositionGetString(POSITION_SYMBOL)!=_Symbol) continue; if(PositionGetInteger(POSITION_MAGIC)!=InpMagic) continue; long type = PositionGetInteger(POSITION_TYPE); if(direction>0 && type!=(long)POSITION_TYPE_BUY) continue; if(direction<0 && type!=(long)POSITION_TYPE_SELL) continue; count++; } return(count); } void CloseOpposite(const int direction) { for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); if(ticket==0) continue; if(!PositionSelectByTicket(ticket)) continue; if(PositionGetString(POSITION_SYMBOL)!=_Symbol) continue; if(PositionGetInteger(POSITION_MAGIC)!=InpMagic) continue; long type = PositionGetInteger(POSITION_TYPE); bool isBuy = (type==(long)POSITION_TYPE_BUY); if(direction>0 && isBuy) continue; if(direction<0 && !isBuy) continue; if(FreezeBlocks(isBuy,PositionGetDouble(POSITION_SL),PositionGetDouble(POSITION_TP))) continue; if(!trade.PositionClose(ticket)) Print("Close opposite failed, ticket ",(string)ticket, " retcode=",(string)trade.ResultRetcode()," ",trade.ResultRetcodeDescription()); else { GlobalVariableDel(GVName(ticket,"stage")); GlobalVariableDel(GVName(ticket,"vol")); } } } //+------------------------------------------------------------------+ //| Open a new trade | //+------------------------------------------------------------------+ bool OpenTrade(const int direction) { double lots = NormalizeLots(InpLots); if(lots<=0.0) { Print("Open skipped: lot size could not be normalized."); return(false); } bool isBuy = (direction>0); double price = (isBuy ? SymbolInfoDouble(_Symbol,SYMBOL_ASK) : SymbolInfoDouble(_Symbol,SYMBOL_BID)); if(price<=0.0) return(false); double slMoney = (isBuy ? InpBuySL : InpSellSL); double tpMoney = (isBuy ? InpBuyTP3 : InpSellTP3); double slDist = MoneyToPrice(slMoney,lots); double tpDist = MoneyToPrice(tpMoney,lots); double sl = 0.0; double tp = 0.0; if(slDist>0.0) sl = (isBuy ? price-slDist : price+slDist); if(tpDist>0.0) tp = (isBuy ? price+tpDist : price-tpDist); AdjustStops(isBuy,sl,tp); bool ok = false; if(isBuy) ok = trade.Buy(lots,_Symbol,0.0,sl,tp,InpComment); else ok = trade.Sell(lots,_Symbol,0.0,sl,tp,InpComment); if(!ok) { Print("Open ",(isBuy ? "BUY" : "SELL")," failed, retcode=",(string)trade.ResultRetcode(), " ",trade.ResultRetcodeDescription()); return(false); } ulong dealTicket = (ulong)trade.ResultOrder(); Print("Opened ",(isBuy ? "BUY" : "SELL")," ",DoubleToString(lots,g_volDigits), " lots at ",DoubleToString(trade.ResultPrice(),g_digits), " order ",(string)dealTicket, " SL ",DoubleToString(sl,g_digits)," TP ",DoubleToString(tp,g_digits)); return(true); } //+------------------------------------------------------------------+ //| Stop-loss move (favorable direction only) | //+------------------------------------------------------------------+ bool MoveStopLoss(const ulong ticket,const bool isBuy,double newSL, double ¤tSL,const double currentTP) { if(newSL<=0.0) return(false); newSL = NormalizeDouble(newSL,g_digits); double tolerance = g_point*0.5; if(isBuy && currentSL>0.0 && newSL<=(currentSL+tolerance)) return(false); if(!isBuy && currentSL>0.0 && newSL>=(currentSL-tolerance)) return(false); double minDist = StopsDistance(); double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID); double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK); if(isBuy && newSL>(bid-minDist)) return(false); if(!isBuy && newSL<(ask+minDist)) return(false); if(FreezeBlocks(isBuy,currentSL,currentTP)) return(false); double tp = (currentTP>0.0 ? NormalizeDouble(currentTP,g_digits) : 0.0); if(!trade.PositionModify(ticket,newSL,tp)) { Print("Modify SL failed, ticket ",(string)ticket, " newSL=",DoubleToString(newSL,g_digits), " retcode=",(string)trade.ResultRetcode()," ",trade.ResultRetcodeDescription()); return(false); } currentSL = newSL; return(true); } //+------------------------------------------------------------------+ //| Partial close | //+------------------------------------------------------------------+ void ClosePartial(const ulong ticket,const double originalVolume, const double currentVolume,const double percent) { if(percent<=0.0 || currentVolume<=0.0) return; double want = FloorLots(originalVolume*percent/100.0); if(want<=0.0) return; if(want>(currentVolume-g_volStep*0.5)) want = FloorLots(currentVolume-g_volStep); if(want=target); return(marketPrice<=target); } //+------------------------------------------------------------------+ //| Manage open positions (every tick) | //+------------------------------------------------------------------+ void ManagePositions() { for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); if(ticket==0) continue; if(!PositionSelectByTicket(ticket)) continue; if(PositionGetString(POSITION_SYMBOL)!=_Symbol) continue; if(PositionGetInteger(POSITION_MAGIC)!=InpMagic) continue; long type = PositionGetInteger(POSITION_TYPE); bool isBuy = (type==(long)POSITION_TYPE_BUY); double curVol = PositionGetDouble(POSITION_VOLUME); double entry = PositionGetDouble(POSITION_PRICE_OPEN); double curSL = PositionGetDouble(POSITION_SL); double curTP = PositionGetDouble(POSITION_TP); double profit = PositionGetDouble(POSITION_PROFIT); double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID); double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK); double market = (isBuy ? bid : ask); if(curVol<=0.0 || entry<=0.0 || market<=0.0) continue; double origVol = OriginalVolume(ticket,curVol); int stage = PositionStage(ticket); double tp1Money = (isBuy ? InpBuyTP1 : InpSellTP1); double tp2Money = (isBuy ? InpBuyTP2 : InpSellTP2); double tp1Price = TargetPrice(entry,isBuy,tp1Money,origVol); double tp2Price = TargetPrice(entry,isBuy,tp2Money,origVol); //--- first target: partial close + lock money above entry if(stage<1 && TargetReached(isBuy,market,tp1Price)) { if(InpUsePartial) ClosePartial(ticket,origVol,curVol,InpPartial1Pct); SetPositionStage(ticket,1); double lockDist = MoneyToPrice(InpLockAfterTP1,origVol); if(lockDist>0.0) MoveStopLoss(ticket,isBuy,(isBuy ? entry+lockDist : entry-lockDist),curSL,curTP); continue; } //--- second target: partial close + SL to the TP1 level if(stage==1 && TargetReached(isBuy,market,tp2Price)) { if(InpUsePartial) ClosePartial(ticket,origVol,curVol,InpPartial2Pct); SetPositionStage(ticket,2); double anchor = (tp1Price>0.0 ? tp1Price : entry); MoveStopLoss(ticket,isBuy,anchor,curSL,curTP); continue; } //--- break-even / money lock if(InpUseBreakEven && InpBETrigger>0.0 && profit>=InpBETrigger) { double lockDist = MoneyToPrice(InpBELock,curVol); double target = (isBuy ? entry+lockDist : entry-lockDist); if(InpBELock<=0.0) target = entry; MoveStopLoss(ticket,isBuy,target,curSL,curTP); } //--- money trailing stop if(InpUseTrailing && InpTrailDist>0.0 && profit>=InpTrailStart) { double trailDist = MoneyToPrice(InpTrailDist,curVol); double stepDist = MoneyToPrice(InpTrailStep,curVol); if(trailDist>0.0) { double candidate = (isBuy ? market-trailDist : market+trailDist); bool improves = true; if(curSL>0.0 && stepDist>0.0) { if(isBuy) improves = (candidate-curSL)>=stepDist; else improves = (curSL-candidate)>=stepDist; } if(improves) MoveStopLoss(ticket,isBuy,candidate,curSL,curTP); } } } } //+------------------------------------------------------------------+ //| Signal execution | //+------------------------------------------------------------------+ void ProcessSignal(const int direction) { if(direction>0 && !InpAllowBuy) return; if(direction<0 && !InpAllowSell) return; if(!TimeAllowed()) return; if(!SpreadAllowed()) return; int opposite = CountPositions(direction>0 ? -1 : 1); if(opposite>0) { if(InpReverseMode==OPPOSITE_IGNORE) return; CloseOpposite(direction); } int same = CountPositions(direction); if(InpMaxPositions>0 && same>=InpMaxPositions) return; int total = CountPositions(0); if(InpMaxPositions>0 && total>=InpMaxPositions && opposite<=0) return; OpenTrade(direction); } //+------------------------------------------------------------------+ //| Tick | //+------------------------------------------------------------------+ void OnTick() { if(g_maHandle==INVALID_HANDLE) return; ManagePositions(); datetime currentBar = (datetime)SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE); bool isNewBar = (currentBar!=g_lastBar); if(isNewBar) { g_lastBar = currentBar; CleanupGlobals(); } if(!InpLive && !isNewBar) return; if(InpLive && g_lastSignalBar==currentBar) return; int direction = 0; if(!GetSignal(direction)) return; if(direction==0) return; if(InpLive) g_lastSignalBar = currentBar; ProcessSignal(direction); } //+------------------------------------------------------------------+