Trying to get this EA to take a % of order once it hits a certain profit, all it seems to do is to take the Pips Above Breakeven as set and nothing else, any help would be greatly appreciated
Thanks
#property copyright""#define RUNS 20#define SLEEP 1000enum ENUM_TIMEFRAMES_MY
{
//None = -1,
Current = 0,
M1 = 1,
M5 = 5,
M15 = 15,
M30 = 30,
H1 = 60,
H4 = 240,
D1 = 1440,
W1 = 10080,
MN1 = 43200
};
//--- input parametersextern ENUM_TIMEFRAMES_MY TF=0; //Time Frameexternbool AccountIsMini = true;
externdouble PartialTP=20.0; //Take Profit Levelexterndouble BreakEvenAdd=5.0; //Pips Above Break Evenexterndouble TrailingStop=0.0; //Trailing Stopexterndouble LotPartClose=0.03; //Lots to Closeexterndouble PartialPercent = 50; //% Lots to Closeextern ENUM_TIMEFRAMES_MY TimeFrameFractal=0; //Time Frame Fractalsexternbool FractalTrail=false; //Fractals Trailing Stopexterndouble PipGap=5.0; //Pip Gapbool First_TP_Level = false;
externint Slippage=3;
/*extern*/int MagicNumber=0; //manua orders onlybool InitRun;
int totalTries=1;
int retryDelay=1000;
double mlt=1;
//+------------------------------------------------------------------+//| expert initialization function |//+------------------------------------------------------------------+int init()
{
//----
mlt=1;
if(Digits==5 || Digits==3 || Digits==1) //5-digit broker
{
mlt *= 10;
PartialTP *= 10;
TrailingStop *= 10;
BreakEvenAdd *= 10;
PipGap *= 10;
}
InitRun=true;
//----return(0);
}
//+------------------------------------------------------------------+//| expert deinitialization function |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
//----Comment("");
//----return;
}
//+------------------------------------------------------------------+//| expert start function |//+------------------------------------------------------------------+int start()
{
//----if(PartialTP>0.0)
{
BreakEven(MagicNumber,PartialTP,BreakEvenAdd);
if(LotPartClose>0.0) PartialClose(MagicNumber,PartialTP,LotPartClose/*,Comm*/);
if(TrailingStop>0.0) TrailingStopRegular(MagicNumber,TrailingStop,0.0,PartialTP);
if(FractalTrail) TrailingStopFractal(MagicNumber,TimeFrameFractal,PipGap,PartialTP);
}
InitRun=false;
//----return(0);
}
//+------------------------------------------------------------------+double ND(double val)
{
return(NormalizeDouble(val, Digits));
}
//+------------------------------------------------------------------+string ErrorToString(int Error)
{
switch(Error)
{
case1: return("No error returned, but the result is unknown.");
case2: return("Common error.");
case3: return("Invalid trade parameters.");
case4: return("Trade server is busy.");
case5: return("Old version of the client terminal.");
case6: return("No connection with trade server.");
case7: return("Not enough rights.");
case8: return("Too frequent requests.");
case9: return("Malfunctional trade operation.");
case64: return("Account disabled.");
case128: return("Trade timeout.");
case129: return("Invalid price.");
case130: return("Invalid stops.");
case131: return("Invalid trade volume.");
case132: return("Market is closed.");
case133: return("Trade is disabled.");
case134: return("Not enough money.");
case135: return("Price changed.");
case136: return("Off quotes.");
case137: return("Broker is busy.");
case138: return("Requote.");
case139: return("Order is locked.");
case140: return("Long positions only allowed.");
case141: return("Too many requests.");
case145: return("Modification denied because order too close to market.");
case146: return("Trade context is busy.");
case147: return("Expirations are denied by broker.");
case148: return("The amount of open and pending orders has reached the limit set by the broker.");
case149: return("An attempt to open a position opposite to the existing one when hedging is disabled.");
case150: return("An attempt to close a position contravening the FIFO rule.");
default: return(StringConcatenate("Error #",Error));
}
}
//+------------------------------------------------------------------+void BreakEven(int MagNum, double BE_Level, double BE_add=0.0)
{
if(BE_Level == 0) return;
int error;
int total = OrdersTotal();
for(int i=total-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) break;
int Type=OrderType();
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagNum && Type<=OP_SELL)
{
double OrderSL=ND(OrderStopLoss());
double OpenPrice=ND(OrderOpenPrice());
double NewSL=0;
if(Type==OP_BUY)
{
if(ND((Bid-OpenPrice)/Point)>=BE_Level && (OpenPrice>OrderSL || OrderSL==0))
{
NewSL=ND(OpenPrice+BE_add*Point);
if(NewSL>OrderSL || OrderSL==0)
if(!OrderModify(OrderTicket(),OrderOpenPrice(),ND(NewSL),OrderTakeProfit(),0,Yellow))
{error=GetLastError(); Print(Symbol()," Break Even error: ",ErrorToString(error));}
continue;
}
}
if(Type==OP_SELL)
{
if(ND((OpenPrice-Ask)/Point)>=BE_Level && (OpenPrice<OrderSL || OrderSL==0))
{
NewSL=ND(OpenPrice-BE_add*Point);
if(NewSL<OrderSL || OrderSL==0)
if(!OrderModify(OrderTicket(),OrderOpenPrice(),ND(NewSL),OrderTakeProfit(),0,Yellow))
{error=GetLastError(); Print(Symbol()," Break Even error: ",ErrorToString(error));}
continue;
}
}
}
}
}
//+------------------------------------------------------------------+void PartialClose(int MgcNmb, double _TP, double _Lot/*, string _Comm*/)
{
int total=OrdersTotal();
for (int i = total-1; i >= 0; i--)
if(OrderSelect(i, SELECT_BY_POS))
{
int type=OrderType();
if(OrderSymbol() == Symbol() && OrderMagicNumber() == MgcNmb && type<=OP_SELL && StringFind(OrderComment(),"#")<0)
{
if(ND((type==OP_BUY?1:-1)*(OrderClosePrice()-OrderOpenPrice()))>=ND(_TP*Point))
{
if (!OrderClose(OrderTicket(), _Lot, OrderClosePrice(), Slippage, clrWhite))
{int error=GetLastError(); Print(Symbol()," Exit Trade error: ",ErrorToString(error));}
}
}
}
return;
}
//+------------------------------------------------------------------+int TrailingStopRegular(int MagNum, double _TrailingStopPip, double _TrailingStopStep, double _TrailingStopTrigger)
{
if(_TrailingStopPip == 0) return (0);
int total=OrdersTotal();
for(int i=total-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
int Type=OrderType();
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagNum && Type<=OP_SELL)
{
double CurStopLoss=OrderStopLoss();
double OpenPrice=OrderOpenPrice();
double NewStoploss = 0.0;
if(Type==OP_BUY) //long
{
NewStoploss = Bid - _TrailingStopPip*Point;
if( (CurStopLoss >= NewStoploss && CurStopLoss != 0.0) || Bid-OpenPrice < _TrailingStopTrigger*Point ) NewStoploss = 0.0;
}
if(Type==OP_SELL) //short
{
NewStoploss = Ask + _TrailingStopPip*Point;
if( (CurStopLoss <= NewStoploss && CurStopLoss != 0.0) || OpenPrice-Ask < _TrailingStopTrigger*Point ) NewStoploss = 0.0;
}
if( NewStoploss != 0.0 )
{
if( MathAbs( CurStopLoss - NewStoploss ) <= Point*_TrailingStopStep ) continue;
else NewStoploss = NormalizeDouble( NewStoploss, Digits);
if(!OrderModify(OrderTicket(),OrderOpenPrice(), NewStoploss, OrderTakeProfit(),0/*,Yellow*/))
{int error=GetLastError(); Print(Symbol()," Modify Order error: ",ErrorToString(error)); continue;}
}
}
}
return (0);
}
//+------------------------------------------------------------------+int TrailingStopFractal(int MagNum, int _TF, double _TrailingStopPip, double _TrailingStopTrigger)
{
if(_TrailingStopPip == 0) return (0);
int total=OrdersTotal();
for(int i=total-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
int Type=OrderType();
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagNum && Type<=OP_SELL)
{
double CurStopLoss=OrderStopLoss();
double OpenPrice=OrderOpenPrice();
double NewStoploss = 0.0;
if(Type==OP_BUY) //long
{
NewStoploss = ND(FractalStopLoss(_TF,OP_BUY) - _TrailingStopPip*Point);//Bid - _TrailingStopPip*Point;if( (CurStopLoss >= NewStoploss && CurStopLoss != 0.0) || Bid-OpenPrice < _TrailingStopTrigger*Point ) NewStoploss = 0.0;
}
if(Type==OP_SELL) //short
{
NewStoploss = ND(FractalStopLoss(_TF,OP_SELL) + _TrailingStopPip*Point);//Ask + _TrailingStopPip*Point;if( (CurStopLoss <= NewStoploss && CurStopLoss != 0.0) || OpenPrice-Ask < _TrailingStopTrigger*Point ) NewStoploss = 0.0;
}
if( NewStoploss != 0.0 )
{
if(!OrderModify(OrderTicket(),OrderOpenPrice(), NewStoploss, OrderTakeProfit(),0,clrRed))
{int error=GetLastError(); Print(Symbol()," Modify Order error: ",ErrorToString(error)); continue;}
}
}
}
return (0);
}
//+------------------------------------------------------------------+double FractalStopLoss(int _tf, int _type)
{
int mode=0;
switch(_type)
{
caseOP_BUY: mode=MODE_LOWER; break;
caseOP_SELL: mode=MODE_UPPER; break;
}
int i=3;
while(i<iBars(NULL,_tf))
{
double fr=iFractals(NULL,_tf,mode,i);
if(fr>0) return(fr);
i++;
}
return(0.0);
}
//+------------------------------------------------------------------+//| Determine number of lots to close//| Uses percentage of current lots//| Checks for mini or standard account//| Inputs://| ol - OrderLots()//| percent - percentage of position to close//+------------------------------------------------------------------+double GetTP_Lots(double ol, double percent)
{
double mLots;
mLots = 0;
if (AccountIsMini)
{
if (ol > 0.1)
{
mLots = MathFloor(ol*percent/10)/10;
if (mLots < 0.1) mLots = 0.1;
}
}
else
{
if (ol > 1)
{
mLots = MathFloor(ol*percent/100);
if (mLots < 1) mLots = 1;
}
}
return(mLots);
}
int CloseOrder(int ticket,double numLots,int cmd)
{
int digits;
double myPrice;
{
if (cmd == OP_BUY) myPrice = MarketInfo(Symbol( ), MODE_BID);
if (cmd == OP_SELL) myPrice = MarketInfo(Symbol( ), MODE_ASK);
digits = MarketInfo(Symbol( ), MODE_DIGITS);
if (digits > 0) myPrice = NormalizeDouble( myPrice, digits);
int error=GetLastError(); Print(Symbol()," Exit Trade error: ",ErrorToString(error));
}
}
// Do Partial Close from TakeProfitbool CheckPartialClose(int cmd, int mTicket, double mLots)
{
double TP_Lots;
TP_Lots = GetTP_Lots(mLots, PartialPercent);
if (TP_Lots > 0)
{
CloseOrder(mTicket,TP_Lots,cmd);
return(false);
}
return(true);
}
//+------------------------------------------------------------------+//| Close Partial Lots |//| Close Partial Lots as levels are reached |//| Inputs: |//| type - Trade type, OP_BUY or OP_SELL |//| ticket - OrderTicket() |//| op - OrderOpenPrice() |//| ol - OrderLots() |//| os - OrderStopLoss() |//| tp - OrderTakeProfit() |//| Returns true if partial lots are closed, false otherwise |//+------------------------------------------------------------------+bool ClosePartialLots(int type, int ticket, double op, double ol, double os, double tp, color mColor = CLR_NONE)
{
double myAsk, myBid;
switch (type)
{
caseOP_BUY:
myBid = MarketInfo(Symbol(),MODE_BID);
if (!First_TP_Level) // Reach 1st TP level
{
if(myBid >= op + PartialTP*mlt)
{
First_TP_Level = true;
if (CheckPartialClose(OP_BUY, ticket, ol)) return(true);
return(false);
}
}
return(false);
break;
caseOP_SELL:
myAsk = MarketInfo(Symbol(),MODE_ASK);
if (!First_TP_Level) // Reach 1st TP level
{
if(myAsk <= op-PartialTP*mlt)
{
First_TP_Level = true;
if (CheckPartialClose(OP_SELL, ticket, ol)) return(true);
return(false);
}
}
}
return(false);
}
Allow the use of cookies to log in to the MQL5.com website.
Please enable the necessary setting in your browser, otherwise you will not be able to log in.
You are signed in. Two-factor authentication has been disabled. Set it up again and scan a new QR code, or continue with two-factor authentication disabled.
Trying to get this EA to take a % of order once it hits a certain profit, all it seems to do is to take the Pips Above Breakeven as set and nothing else, any help would be greatly appreciated
Thanks