posInfo.Select(symbol_bn);
if (!ecn) {
Print("M-",_Symbol, " Position Executed Successfully! Position Type=", PositionTypetoString(pType), ". Symbol=", symbol_bn);
Print("M-",_Symbol, " Price=",DoubleToString(price_bn,digits_bn), " FillPrice=", DoubleToString(posInfo.PriceOpen(),digits_bn), " Slippage=",DoubleToString((posInfo.PriceOpen()-price_bn),digits_bn));
Print("M-",_Symbol, " Account Equity=",AccountInfoDouble(ACCOUNT_EQUITY),". Account Balance=",AccountInfoDouble(ACCOUNT_BALANCE),". Account Free Margin = ",AccountInfoDouble(ACCOUNT_FREEMARGIN));
Sleep(SleepTime);
if (SendMailMode)
{
//Prepare email
subject = "EA: ";
StringConcatenate(subject,EAName,". ",symbol_bn," ",PositionTypetoString(pType)," position executed); ");
mailstring = "email generated by Expert Advisor Visual Wizard v3.1 \n";
StringConcatenate(mailstring, "Server Time=",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),". Terminal Time=",TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS),"\n");
StringConcatenate(mailstring, "M-Order Executed Successfully!\nOrder Info : \n Order Type=", PositionTypetoString(pType), ".\n Symbol=", symbol_bn, ".\n Lot Size=",lotsize_bn,
".\n Price=",DoubleToString(price_bn,digits_bn), ".\n FillPrice=", DoubleToString(posInfo.PriceOpen(),digits_bn), ".\n _Slippage=",DoubleToString((posInfo.PriceOpen()-price_bn),digits_bn), ".\n SL=",DoubleToString(posInfo.StopLoss(),digits_bn),".\n TP=",DoubleToString(posInfo.TakeProfit(),digits_bn), ".\n Order time=",posInfo.Time(),
".\n Maximum Number of deals:", MaxVolumePosition,".\n Current Volume:",PositionVolume(symbol_bn));
SendMail(subject, mailstring);
}
if (PlaySounds)
{
PlaySound(MySound);
}
} else {
Print("M-",_Symbol, " ECN Step 1 Order Executed Successfully without stops! Position Type=", PositionTypetoString(pType), ". Symbol=", symbol_bn);
Print("M-",_Symbol, " Price=",DoubleToString(price_bn,digits_bn), " FillPrice=", DoubleToString(posInfo.PriceOpen(),digits_bn), " Slippage=",DoubleToString((posInfo.PriceOpen()-price_bn),digits_bn));
Print("M-",_Symbol, " ECN Step 2 Adding stops...");
success = trade.PositionModify(symbol_bn, stoploss_bn, takeprofit_bn);
errorcode_bn = trade.ResultRetcode();
//Print(errorcode_bn," ",ErrorCodeDescription(errorcode_bn));
//if(success && (errorcode_bn==TRADE_RETCODE_PLACED || errorcode_bn==TRADE_RETCODE_DONE) ) {
if( (errorcode_bn==TRADE_RETCODE_PLACED || errorcode_bn==TRADE_RETCODE_DONE) && (errorcode_bn!=TRADE_RETCODE_INVALID_STOPS) ) {
Print("M-",_Symbol, " ECN Position Step 2 Stops added Successfully! Position Type=", PositionTypetoString(pType), ". Symbol=", symbol_bn);
if (PlaySounds)
{
PlaySound(MySound);
}
if (SendMailMode)
{
//Prepare email
subject = "EA: ";
StringConcatenate(subject,EAName,". ",symbol_bn," ",PositionTypetoString(pType)," position executed); ");
mailstring = "email generated by Expert Advisor Visual Wizard v3.1 \n";
StringConcatenate(mailstring, "Server Time=",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),". Terminal Time=",TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS),"\n");
StringConcatenate(mailstring, "M-Order Executed Successfully!\nOrder Info : \n Order Type=", PositionTypetoString(pType), ".\n Symbol=", symbol_bn, ".\n Lot Size=",lotsize_bn,
".\n Price=",DoubleToString(price_bn,digits_bn), ".\n FillPrice=", DoubleToString(posInfo.PriceOpen(),digits_bn), ".\n _Slippage=",DoubleToString((posInfo.PriceOpen()-price_bn),digits_bn), ".\n SL=",DoubleToString(posInfo.StopLoss(),digits_bn),".\n TP=",DoubleToString(posInfo.TakeProfit(),digits_bn), ".\n Order time=",posInfo.Time(),
".\n Maximum Number of deals:", MaxVolumePosition,".\n Current Volume:",PositionVolume(symbol_bn));
SendMail(subject, mailstring);
}
} else {
Print("M-",_Symbol, " ECN ERROR: Position Executed Successfully but stops may be missing! Position Type=", PositionTypetoString(pType), ". Symbol=", symbol_bn);
Print("M-",_Symbol, " Price=",DoubleToString(price_bn,digits_bn), " FillPrice=", DoubleToString(posInfo.PriceOpen(),digits_bn), " Slippage=",DoubleToString((posInfo.PriceOpen()-price_bn),digits_bn));
Print("M-",_Symbol, " Account Equity=",AccountInfoDouble(ACCOUNT_EQUITY),". Account Balance=",AccountInfoDouble(ACCOUNT_BALANCE),". Account Free Margin = ",AccountInfoDouble(ACCOUNT_FREEMARGIN));
if (PlaySounds)
{
PlaySound(MySound);
}
Sleep(SleepTime);
if (SendMailMode)
{
//Prepare email
subject = "EA: ";
StringConcatenate(subject,EAName,". ",symbol_bn," ",PositionTypetoString(pType)," position executed); ");
mailstring = "email generated by Expert Advisor Visual Wizard v3.1 \n";
StringConcatenate(mailstring, "Server Time=",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),". Terminal Time=",TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS),"\n");
StringConcatenate(mailstring, "M-Order Executed Successfully for ECN but stops may be missing!\nOrder Info : \n Order Type=", PositionTypetoString(pType), ".\n Symbol=", symbol_bn, ".\n Lot Size=",lotsize_bn,
".\n Price=",DoubleToString(price_bn,digits_bn), ".\n FillPrice=", DoubleToString(posInfo.PriceOpen(),digits_bn), ".\n _Slippage=",DoubleToString((posInfo.PriceOpen()-price_bn),digits_bn), ".\n SL=",DoubleToString(posInfo.StopLoss(),digits_bn),".\n TP=",DoubleToString(posInfo.TakeProfit(),digits_bn), ".\n Order time=",posInfo.Time(),
".\n Maximum Number of deals:", MaxVolumePosition,".\n Current Volume:",PositionVolume(symbol_bn));
SendMail(subject, mailstring);
}
}
}
//Paint arrows
ObjCount++;
if (golong_bn)
{
if (!ObjectCreate(0, "Molanis"+ObjCount, OBJ_ARROW_BUY, 0, TimeCurrent(), price_bn))
{
Print("M-",_Symbol," Warning: ARROW UP marker coudn't be created.");
} else {
ObjectSetInteger(0, "Molanis"+ObjCount, OBJPROP_COLOR, Green);
Print("M-",_Symbol," Warning: ARROW UP marker created at ",price_bn, " named Molanis"+ObjCount);
ChartRedraw(0);
}
} else {
if (!ObjectCreate(0, "Molanis"+ObjCount, OBJ_ARROW_SELL, 0, TimeCurrent(), price_bn))
{
Print("M-",_Symbol," Warning: ARROW DOWN marker coudn't be created.");
} else {
ObjectSetInteger(0, "Molanis"+ObjCount, OBJPROP_COLOR, Red);
Print("M-",_Symbol," Warning: ARROW DOWN marker created at ",price_bn, " named Molanis"+ObjCount);
ChartRedraw(0);
}
}
return true;
}
else
{
//Retry if ERROR can be solved
if(errorcode_bn==TRADE_RETCODE_CONNECTION
|| errorcode_bn==TRADE_RETCODE_TIMEOUT || errorcode_bn==TRADE_RETCODE_INVALID_PRICE || errorcode_bn==TRADE_RETCODE_PRICE_OFF || errorcode_bn==TRADE_RETCODE_PRICE_CHANGED || errorcode_bn==TRADE_RETCODE_REQUOTE || errorcode_bn==TRADE_RETCODE_REJECT
|| errorcode_bn==TRADE_RETCODE_ERROR || errorcode_bn==TRADE_RETCODE_INVALID || errorcode_bn==TRADE_RETCODE_INVALID_VOLUME || errorcode_bn==TRADE_RETCODE_INVALID_STOPS || errorcode_bn==TRADE_RETCODE_INVALID_FILL) {
Print("M-",_Symbol, " ERROR: Server error. Sending order to server again. Retry intent number = ",tries);
tries++;
if (tries>MaxOrderRetry+1) {
Print("M-",_Symbol," ERROR: Could not open new position. Error=",errorcode_bn, " ",trade.ResultRetcodeDescription(),". Order Info : Position Type=", PositionTypetoString(pType) , ". Symbol=", symbol_bn, ". Lot Size=",lotsize_bn,
". Price=",DoubleToString(price_bn,digits_bn),". Stoploss = ",DoubleToString(stoploss_bn,digits_bn),". Takeprofit = ",DoubleToString(takeprofit_bn,digits_bn));
if (ShowWarnings) Alert("M-"+_Symbol+ " ERROR: Could not open new position. Error=",errorcode_bn, " ",trade.ResultRetcodeDescription(),". Order Info : Position Type=", PositionTypetoString(pType) , ". Symbol=", symbol_bn, ". Lot Size=",lotsize_bn,
". Price=",DoubleToString(price_bn,digits_bn),". Stoploss = ",DoubleToString(stoploss_bn,digits_bn),". Takeprofit = ",DoubleToString(takeprofit_bn,digits_bn));
if (SendMailMode)
{
subject = "EA: ";
StringConcatenate(subject,EAName," ",symbol_bn," ", PositionTypetoString(pType)," position FAILED");
mailstring = "email generated by Expert Advisor Visual Wizard v3.1 \n";
StringConcatenate(mailstring, "Server Time=",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),". Terminal Time=",TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS),"\n");
StringConcatenate(mailstring, "WARNING: Could not open new position.\n Error=",errorcode_bn, "\n", trade.ResultRetcodeDescription(),".\n Order Info :\nOrder Type=", PositionTypetoString(pType), ".\n Symbol=", symbol_bn, ".\n Lot Size=",lotsize_bn,
". Price=",DoubleToString(price_bn,digits_bn),". Stoploss = ",DoubleToString(stoploss_bn,digits_bn),". Takeprofit = ",DoubleToString(takeprofit_bn,digits_bn));
SendMail(subject, mailstring);
}
return false;
}
Sleep(SleepTime);
} else {
Print("M-",_Symbol," ERROR: Could not open new position. Error=",errorcode_bn, " ",trade.ResultRetcodeDescription(),". Order Info : Position Type=", PositionTypetoString(pType) , ". Symbol=", symbol_bn, ". Lot Size=",lotsize_bn,
". Price=",DoubleToString(price_bn,digits_bn),". Stoploss = ",DoubleToString(stoploss_bn,digits_bn),". Takeprofit = ",DoubleToString(takeprofit_bn,digits_bn));
if (ShowWarnings) Alert("M-"+_Symbol+ " ERROR: Could not open new position. Error=",errorcode_bn, " ",trade.ResultRetcodeDescription(),". Order Info : Position Type=", PositionTypetoString(pType) , ". Symbol=", symbol_bn, ". Lot Size=",lotsize_bn,
". Price=",DoubleToString(price_bn,digits_bn),". Stoploss = ",DoubleToString(stoploss_bn,digits_bn),". Takeprofit = ",DoubleToString(takeprofit_bn,digits_bn));
if (SendMailMode)
{
subject = "EA: ";
StringConcatenate(subject,EAName," ",symbol_bn," ", PositionTypetoString(pType)," position FAILED");
mailstring = "email generated by Expert Advisor Visual Wizard v3.1 \n";
StringConcatenate(mailstring, "Server Time=",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),". Terminal Time=",TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS),"\n");
StringConcatenate(mailstring, "WARNING: Could not open new position.\n Error=",errorcode_bn, "\n", trade.ResultRetcodeDescription(),".\n Order Info :\nOrder Type=", PositionTypetoString(pType), ".\n Symbol=", symbol_bn, ".\n Lot Size=",lotsize_bn,
". Price=",DoubleToString(price_bn,digits_bn),". Stoploss = ",DoubleToString(stoploss_bn,digits_bn),". Takeprofit = ",DoubleToString(takeprofit_bn,digits_bn));
SendMail(subject, mailstring);
}
return false;
}
}
} //close while
return false;
}
//Lot Management changes lot size. Part of money management
/*
*** Generated with Expert Advisor Visual Wizard 3.1 ***
***
www.molanis.com ***
*** Released 2010-06-20 ***
*/
double LotManagement(string symbol_lot,double lot_lot)
{
double lot= lot_lot; // get defined lotsize
if (!UseLotManagement) //if not using lot management
{
if(MathAbs(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP)-MathRound(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP) ))>1.0E-10)
{
lot=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP)*NormalizeDouble(lot/SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP),0);
Print("M-",_Symbol," Warning: Your lot size of ",lot_lot," is not a multiple of minimal step ",SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP),". Lot size changed to ",lot);
}
if (lot<SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN))
{
lot=SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN);
Print("M-",_Symbol," Warning: Your lot size of ",lot_lot," is lower than the minimum size allowed by the server. Lot size changed to ",lot);
return(lot);
}
if (lot>SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX))
{
lot= SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX);
Print("M-",_Symbol," Warning: Your lot size of ",lot_lot," is higher than the maximum size allowed by the server. Lot size changed to ",lot);
return(lot);
}
return(lot);
}
//calculate number of losses/wins without a break
int losses = 0, gains=0; // number of losses/gain orders without a break
ulong ticket;
int ordersnumb=HistoryDealsTotal();
//losses
HistorySelect(0, TimeCurrent());
for(int i = ordersnumb-1; i >= 0; i--)
{
ticket = HistoryDealGetTicket(i);
if(ticket == 0)
{
Print("M-",_Symbol," Error in history when running Lot Management!");
break;
}
if(HistoryDealGetString(ticket,DEAL_SYMBOL)!=symbol_lot || HistoryDealGetInteger(ticket,DEAL_TYPE)>DEAL_TYPE_SELL) continue;
if(HistoryDealGetDouble(ticket,DEAL_PROFIT) > 0) break;
if(HistoryDealGetDouble(ticket,DEAL_PROFIT) < 0) losses++;
}
//wins
HistorySelect(0, TimeCurrent());
ordersnumb=HistoryDealsTotal();
for(int i = ordersnumb-1;i >= 0;i--)
{
if(!(ticket = HistoryDealGetTicket(i)))
{
Print("M-",_Symbol," Error in history when running Lot Management!");
break;
}
if(HistoryDealGetString(ticket,DEAL_SYMBOL)!=symbol_lot || HistoryDealGetInteger(ticket,DEAL_TYPE)>DEAL_TYPE_SELL) continue;
if(HistoryDealGetDouble(ticket,DEAL_PROFIT) < 0) break;
if(HistoryDealGetDouble(ticket,DEAL_PROFIT) > 0) gains++;
}
// 1 - Uses Decrease factor
// 2 - Uses a fix factor 75%,50%.25%
//set normalizedouble
int tmpdecimal=1;
if (IsMicroAccount)
{
tmpdecimal=2;
}
//adjusting lot size
if (LotManagementType==1)
{
if(ReductionFactor>0)
{
if(losses>=DecreaseLotAfterLoss) //decrease lot after DecreaseLotAfterLoss losses in a row
{
lot=NormalizeDouble(lot-(lot*losses/ReductionFactor),tmpdecimal);
if(MathAbs(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP)-MathRound(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP) ))>1.0E-10)
{
lot=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP)*NormalizeDouble(lot/SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP),0);
//Print("M-",_Symbol," Warning: Your lot size of ",lot_lot," has a wrong lot step. Should be ",SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP),". Lot size changed to ",lot);
}
if (lot<SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN))
{
lot=SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN);
Print("M-",_Symbol," MoneyManagementType=1. Loss number=",losses,". Lot adjusted to minimum size allowed by server of ",lot, " from ",lot_lot);
} else if (lot>SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX))
{
lot=SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX);
Print("M-",_Symbol," MoneyManagementType=1. Loss number=",losses,". Lot adjusted to maximum size allowed by server of ",lot, " from ",lot_lot);
}
else
{
Print("M-",_Symbol," MoneyManagementType=1. Loss number=",losses,". Lot adjusted to ",lot, " from ",lot_lot);
}
}
}
}
else if (LotManagementType==2)
{
if (losses==2)
{
lot=NormalizeDouble(0.75*lot,tmpdecimal);
if(MathAbs(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP)-MathRound(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP) ))>1.0E-10)
{
lot=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP)*NormalizeDouble(lot/SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP),0);
//Print("M-",_Symbol," Warning: Your lot size of ",lot_lot," has a wrong lot step. Should be ",SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP),". Lot size changed to ",lot);
}
if (lot<SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN))
{
lot=SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN);
Print("M-",_Symbol," MoneyManagementType=2. Two losses in a row. Loss number=",losses,". Lot adjusted to minimum size allowed by server of ",lot, " from ",lot_lot);
} else if (lot>SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX))
{
lot=SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX);
Print("M-",_Symbol," MoneyManagementType=2. Two losses in a row. Loss number=",losses,". Lot adjusted to maximum size allowed by server of ",lot, " from ",lot_lot);
}
else
{
Print("M-",_Symbol," MoneyManagementType=2. Two losses in a row. Adjust to 75% of previous lot size. Loss number=",losses,". Lot adjusted to ",lot, " from ",lot_lot);
}
}
if (losses==3)
{
lot=NormalizeDouble(0.50*lot,tmpdecimal);
if(MathAbs(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP)-MathRound(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP) ))>1.0E-10)
{
lot=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP)*NormalizeDouble(lot/SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP),0);
//Print("M-",_Symbol," Warning: Your lot size of ",lot_lot," has a wrong lot step. Should be ",SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP),". Lot size changed to ",lot);
}
if (lot<SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN))
{
lot=SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN);
Print("M-",_Symbol," MoneyManagementType=2. Three losses in a row. Loss number=",losses,". Lot adjusted to minimum size allowed by server of ",lot, " from ",lot_lot);
} else if (lot>SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX))
{
lot=SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX);
Print("M-",_Symbol," MoneyManagementType=2. Three losses in a row. Loss number=",losses,". Lot adjusted to maximum size allowed by server of ",lot, " from ",lot_lot);
}
else
{
Print("M-",_Symbol," MoneyManagementType=2. Three losses in a row. Adjust to 50% of previous lot size. Loss number=",losses,". Lot adjusted to ",lot, " from ",lot_lot);
}
}
if (losses>=4)
{
lot=NormalizeDouble(0.25*lot,tmpdecimal);
if(MathAbs(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP)-MathRound(lot/SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP) ))>1.0E-10)
{
lot=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP)*NormalizeDouble(lot/SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP),0);
//Print("M-",_Symbol," Warning: Your lot size of ",lot_lot," has a wrong lot step. Should be ",SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_STEP),". Lot size changed to ",lot);
}
if (lot<SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN))
{
lot=SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MIN);
Print("M-",_Symbol," MoneyManagementType=2. More than Three losses in a row. Loss number=",losses,". Lot adjusted to minimum size allowed by server of ",lot, " from ",lot_lot);
} else if (lot>SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX))
{
lot=SymbolInfoDouble(symbol_lot,SYMBOL_VOLUME_MAX);
Print("M-",_Symbol," MoneyManagementType=2. More than Three losses in a row. Loss number=",losses,". Lot adjusted to maximum size allowed by server of ",lot, " from ",lot_lot);
}
else
{
Print("M-",_Symbol," MoneyManagementType=2. More than Three losses in a row. Adjust to 25% of previous lot size. Loss number=",losses,". Lot adjusted to ",lot, " from ",lot_lot);
}
}
}
return(lot);
}
//PositionTypetoString This function Returs the string value of the order type
/*
*** Generated with Expert Advisor Visual Wizard 3.1 ***
***
www.molanis.com ***
*** Released 2010-06-20 ***
*/
string PositionTypetoString(ENUM_POSITION_TYPE ordertypecode)
{
if (ordertypecode == POSITION_TYPE_BUY)
return("POSITION_TYPE_BUY");
if (ordertypecode == POSITION_TYPE_SELL)
return("POSITION_TYPE_SELL");
return("Unknow order type");
}
//isTradingPossible checks if trading is possible.
/*
*** Generated with Expert Advisor Visual Wizard 3.1 ***
***
www.molanis.com ***
*** Released 2010-06-20 ***
*/
bool isTradingPossible()
{
//Check if trading is possible
bool tmpresponse=true;
if(!TerminalInfoInteger(TERMINAL_CONNECTED))
{
Print("M-",_Symbol, " URGENT ACTION REQUIRED : There is no connection to the server!");
if (ShowWarnings) Alert("URGENT ACTION REQUIRED : There is no connection to the server!");
tmpresponse=false;
}
if(IsStopped())
{
Print("M-",_Symbol, " ERROR : EA was commanded to stop its operation!");
if (ShowWarnings) Alert("ERROR : EA was commanded to stop its operation!");
tmpresponse=false;
}
if (!MQL5InfoInteger(MQL5_TRADE_ALLOWED)) {
Print("M-",_Symbol, " ERROR : Trading is not allowed at this moment!");
if (ShowWarnings) Alert("ERROR : Trading is not allowed at this moment!");
tmpresponse=false;
}
return(tmpresponse);
}
// CheckTrailingStop
// To adjust trailing stops
/*
*** Generated with Expert Advisor Visual Wizard 3.1 ***
***
www.molanis.com ***
*** Released 2010-06-20 ***
*/
int CheckTrailingStop(string symbol_ts, ENUM_POSITION_TYPE postype_ts,int magicnumber_ts, double tralingstop_ts)
{
if (tralingstop_ts <= 0)
return(0);
//verify type is ok
if(postype_ts != POSITION_TYPE_BUY && postype_ts != POSITION_TYPE_SELL)
{
Print("M-",_Symbol, " Check Trailing Stop failed. Order type is wrong.");
return(-1);
}
int errorcode_ts = 0;
CTrade trade;
CPositionInfo posInfo;
CSymbolInfo symInfo;
symInfo.Name(symbol_ts);
//Verify TS
if(tralingstop_ts*PipMultiplier<symInfo.StopsLevel() && tralingstop_ts>0)
{
Print("M-",_Symbol," Error: Trailing Stop must be greater than ",DoubleToString(symInfo.StopsLevel(),symInfo.Digits())," Please change your trailing stop in the EA properties before running this EA in a real account");
if (ShowWarnings) Alert("M-"+_Symbol+" Error: Trailing Stop must be greater than "+DoubleToString(symInfo.StopsLevel(),symInfo.Digits())+" Please change your trailing stop in the EA properties before running this EA in a real account");
}
if (posInfo.Select(symbol_ts))
if (posInfo.Magic() == magicnumber_ts)
{
symInfo.RefreshRates();
if (posInfo.PositionType() == POSITION_TYPE_SELL)
if (posInfo.PriceOpen() - symInfo.Ask() > tralingstop_ts * PipMultiplier * symInfo.Point())
if (posInfo.StopLoss() == 0 || posInfo.StopLoss() > symInfo.Ask() + tralingstop_ts * PipMultiplier * symInfo.Point())
{
double oldStop = posInfo.StopLoss(),
newStop = NormalizeDouble(symInfo.Ask() + tralingstop_ts * PipMultiplier * symInfo.Point(),symInfo.Digits());
if (trade.PositionModify(posInfo.Symbol(), newStop, posInfo.TakeProfit()))
{
Print("M-",_Symbol," Order to change SL using trailing stop for short position was accepted. Old SL=",DoubleToString(oldStop,symInfo.Digits())," New SL=",DoubleToString(newStop,symInfo.Digits()), " Ask=",symInfo.Ask());
}
else
{
errorcode_ts = trade.ResultRetcode();
Print("M-",_Symbol," Warning: Could not change SL value with trailing stop for short position. Error:",errorcode_ts," ");
Print("M-",_Symbol, " ",ErrorCodeDescription(errorcode_ts)," ",trade.ResultComment());
}
}
if (posInfo.PositionType() == POSITION_TYPE_BUY)
if (symInfo.Bid() - posInfo.PriceOpen() > tralingstop_ts * PipMultiplier * symInfo.Point())
if (posInfo.StopLoss() == 0 || posInfo.StopLoss() < symInfo.Bid() - tralingstop_ts * PipMultiplier * symInfo.Point())
{
double oldStop = posInfo.StopLoss(),
newStop = NormalizeDouble(symInfo.Bid() - tralingstop_ts * PipMultiplier * symInfo.Point(),symInfo.Digits());
if (trade.PositionModify(posInfo.Symbol(), newStop, posInfo.TakeProfit()))
{
Print("M-",_Symbol," Order to change SL using trailing stop for long position was accepted.. Old SL=",DoubleToString(oldStop,symInfo.Digits())," New SL=",DoubleToString(newStop,symInfo.Digits()), " Bid=",symInfo.Bid());
}
else
{
errorcode_ts = trade.ResultRetcode();
Print("M-",_Symbol," Warning: Could not change SL value with trailing stop for long position. Error:",errorcode_ts," ");//,ErrorDescription(errorcode_ts));
Print("M-",_Symbol, " ",ErrorCodeDescription(errorcode_ts)," ",trade.ResultComment());
}
}
}
return(1);
}
//+------------------------------------------------------------------+
//| Returns the size of position of pair - if it fails it returns -1 |
//+------------------------------------------------------------------+
double PositionVolume(string mysymbol)
{
CSymbolInfo symInfo;
bool Pos=PositionSelect(mysymbol);
if(Pos)
return(PositionGetDouble(POSITION_VOLUME));
else
{
symInfo.Name(mysymbol);
symInfo.RefreshRates();
Pos=PositionSelect(mysymbol);
if(Pos)
return(PositionGetDouble(POSITION_VOLUME));
else {
symInfo.Name(mysymbol);
symInfo.RefreshRates();
Pos=PositionSelect(mysymbol);
if(Pos)
return(PositionGetDouble(POSITION_VOLUME));
else {
Print("M-",_Symbol," Warning: Could not get position volume. Assigning volume of 0");
return(0);
}
}
}
}
int CLOSELONG(string symbol_s)
{
ClosePosition(symbol_s,POSITION_TYPE_BUY,MagicNumberLong);
Sleep(SleepTime);
return(0);
}
int CLOSESHORT(string symbol_b)
{
ClosePosition(symbol_b, POSITION_TYPE_SELL,MagicNumberShort);
Sleep(SleepTime);
return(0);
}
string getUnitReasonText(int reasonCode)
{
string text="";
switch(reasonCode)
{
case REASON_ACCOUNT:
text="Account was changed";break;
case REASON_CHARTCHANGE:
text="Symbol or timeframe was changed";break;
case REASON_CHARTCLOSE:
text="Chart was closed";break;
case REASON_PARAMETERS:
text="Input-parameter was changed";break;
case REASON_RECOMPILE:
text="Program "+__FILE__+" was recompiled";break;
case REASON_REMOVE:
text="Program "+__FILE__+" was removed from chart";break;
case REASON_TEMPLATE:
text="New template was applied to chart";break;
default:text="Unknow reason";
}
return text;
}
//+------------------------------------------------------------------+
//| returns trade server return code description |
//+------------------------------------------------------------------+
string ErrorCodeDescription(int return_code)
{
//---
switch(return_code)
{
//The return code 10009 shows that the OrderSend request was completed successfully, while 10008 shows that our order has been placed.
case TRADE_RETCODE_REQUOTE: return("Requote");
case TRADE_RETCODE_REJECT: return("Request rejected");
case TRADE_RETCODE_CANCEL: return("Request canceled by trader");
case TRADE_RETCODE_PLACED: return("Order placed");
case TRADE_RETCODE_DONE: return("Request is completed");
case TRADE_RETCODE_DONE_PARTIAL: return("Request is partially completed");
case TRADE_RETCODE_ERROR: return("Request processing error");
case TRADE_RETCODE_TIMEOUT: return("Request canceled by timeout");
case TRADE_RETCODE_INVALID: return("Invalid request");
case TRADE_RETCODE_INVALID_VOLUME: return("Invalid volume in the request");
case TRADE_RETCODE_INVALID_PRICE: return("Invalid price in the request");
case TRADE_RETCODE_INVALID_STOPS: return("Invalid stops in the request");
case TRADE_RETCODE_TRADE_DISABLED: return("Trade is disabled");
case TRADE_RETCODE_MARKET_CLOSED: return("Market is closed");
case TRADE_RETCODE_NO_MONEY: return("There is not enough money to fulfill the request");
case TRADE_RETCODE_PRICE_CHANGED: return("Prices changed");
case TRADE_RETCODE_PRICE_OFF: return("There are no quotes to process the request");
case TRADE_RETCODE_INVALID_EXPIRATION: return("Invalid order expiration date of in the request");
case TRADE_RETCODE_ORDER_CHANGED: return("Order state changed");
case TRADE_RETCODE_TOO_MANY_REQUESTS: return("Too frequent requests");
case TRADE_RETCODE_NO_CHANGES: return("No changes in request");
case TRADE_RETCODE_SERVER_DISABLES_AT: return("Autotrading disabled by server");
case TRADE_RETCODE_CLIENT_DISABLES_AT: return("Autotrading disabled by client terminal");
case TRADE_RETCODE_LOCKED: return("Request locked for processing");
case TRADE_RETCODE_FROZEN: return("Order or position frozen");
case TRADE_RETCODE_INVALID_FILL: return("Invalid order filling type");
case TRADE_RETCODE_CONNECTION: return("No connection with the trade server");
case TRADE_RETCODE_ONLY_REAL: return("Operation is allowed only for live accounts");
case TRADE_RETCODE_LIMIT_ORDERS: return("The number of pending orders has reached the limit");
case TRADE_RETCODE_LIMIT_VOLUME: return("The volume of orders and positions for the symbol has reached the limit");
}
//---
return("Invalid return code of the trade server");
}
//+------------------------------------------------------------------+
//| Get Low for specified bar index |
//+------------------------------------------------------------------+
double iLow(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double low=0;
ArraySetAsSeries(Low,true);
int copied=CopyLow(symbol,timeframe,0,Bars(symbol,timeframe),Low);
if(copied>0 && index<copied) low=Low[index];
return(low);
}
//+------------------------------------------------------------------+
//| Get the High for specified bar index |
//+------------------------------------------------------------------+
double iHigh(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double high=0;
ArraySetAsSeries(High,true);
int copied=CopyHigh(symbol,timeframe,0,Bars(symbol,timeframe),High);
if(copied>0 && index<copied) high=High[index];
return(high);
}
//+------------------------------------------------------------------+
//| Get the Open for specified bar index |
//+------------------------------------------------------------------+
double iOpen(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double open=0;
ArraySetAsSeries(Open,true);
int copied=CopyOpen(symbol,timeframe,0,Bars(symbol,timeframe),Open);
if(copied>0 && index<copied) open=Open[index];
return(open);
}
//+------------------------------------------------------------------+
//| Get the Close for specified bar index |
//+------------------------------------------------------------------+
double iClose(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double close=0;
ArraySetAsSeries(Close,true);
int copied=CopyClose(symbol,timeframe,0,Bars(symbol,timeframe),Close);
if(copied>0 && index<copied) close=Close[index];
return(close);
}
//----functions end
//}//end molanis
/*Summary
//Indicator Handle
int iRSI_L1;
int iRSI_L2;
//Indicator Arrays
double iRSI_L1_Value[];
double iRSI_L2_Value[];
//Indicator Handle Get Value
iRSI_L1=iRSI("EURUSD",PERIOD_M1,2,PRICE_CLOSE);
if (iRSI_L1 < 0)
{
Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again.");
}
iRSI_L2=iRSI("EURUSD",PERIOD_M1,2,PRICE_CLOSE);
if (iRSI_L2 < 0)
{
Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again.");
}
//Indicator Set as Series
ArraySetAsSeries(iRSI_L1_Value, true);
ArraySetAsSeries(iRSI_L2_Value, true);
//Indicator Release
IndicatorRelease(iRSI_L1);
IndicatorRelease(iRSI_L2);
//Indicator CopyBuffer
if ( CopyBuffer(iRSI_L1,0,0,1,iRSI_L1_Value)!=1 )
{
if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar.");
return;
}
if ( CopyBuffer(iRSI_L2,0,0,1,iRSI_L2_Value)!=1 )
{
if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar.");
return;
}
//Conditions
if ( (iRSI_L2_Value[0] > 99.90000) ) { SELL(Symbol(),S_Symbol_LS_0,S_Symbol_TP_0,S_Symbol_SL_0,S_Symbol_TS_0,"if ( (iRSI_L2_Value[0] > 99.90000) )") ;}
if ( (iRSI_L1_Value[0] < 0.10000) ) { BUY(Symbol(),B_Symbol_LS_0,B_Symbol_TP_0,B_Symbol_SL_0,B_Symbol_TS_0,"if ( (iRSI_L1_Value[0] < 0.10000) )") ;}
//Alerts
if ( (iRSI_L2_Value[0] > 99.90000) ) { MolanisAlert("if ( (iRSI_L2_Value[0] > 99.90000) )","SELL(Symbol(),1.0,2,2,0)",Symbol()) ;}
if ( (iRSI_L1_Value[0] < 0.10000) ) { MolanisAlert("if ( (iRSI_L1_Value[0] < 0.10000) )","BUY(Symbol(),1.0,2,2,0)",Symbol()) ;}
*/