//+------------------------------------------------------------------+ // DO NOT DELETE THIS HEADER // DELETING THIS HEADER IS COPYRIGHT INFRIGMENT // Copyright © 2009-2011, Molanis // Expert Advisor Visual Wizard 3.1 // http://www.molanis.com // // THIS EA CODE HAS BEEN GENERATED USING Expert Advisor Visual Wizard V3.1 // on Thu Aug 04 10:57:14 CEST 2016 // Disclaimer: This EA is provided to you "AS-IS", and Molanis disclaims any warranty // or liability obligations to you of any kind. // UNDER NO CIRCUMSTANCES WILL MOLANIS BE LIABLE TO YOU, OR ANY OTHER PERSON OR ENTITY, // FOR ANY LOSS OF USE, REVENUE OR PROFIT, LOST OR DAMAGED DATA, OR OTHER COMMERCIAL OR // ECONOMIC LOSS OR FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, STATUTORY, PUNITIVE, // EXEMPLARY OR CONSEQUENTIAL DAMAGES WHATSOEVER RELATED TO YOUR USE OF THIS EA OR // Expert Advisor Visual Wizard // Because software is inherently complex and may not be completely free of errors, you are // advised to verify this EA. Before using this EA, please read the Expert Advisor Visual Wizard // license for a complete understanding of Molanis' disclaimers. // USE THIS EA AT YOUR OWN RISK. // // Before adding this expert advisor to a chart, make sure there are NO // open positions. // DO NOT DELETE THIS HEADER // DELETING THIS HEADER IS COPYRIGHT INFRIGMENT //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| EA Notes | /*| */ //+------------------------------------------------------------------+ //Strategy Comments #property copyright "Created with Molanis Software" #property link "http://www.molanis.com" #property version "3.1" #property description "This EA was created with Expert Advisor Visual Wizard v3.1" #property description "Do not forget to use the MetaTrader inputs to optimize this EA" #define SleepTime 900 //To sleep for a while before retrying order execution //+------------------------------------------------------------------+ //| initial setup | //+------------------------------------------------------------------+ // The main purpose of this section is to initialize trading variables. // //+--- input parameters ---------------------------------------------+ // Used to activate/deactivate/select options // General Variables input string EAName="3way"; // Expert Advisor Name input bool IsMicroAccount = true; // Define if account is micro or standard input bool CompletedBars = true; // Define execution by bars or ticks input bool TradeOrAlert = true; // Define execution. True allows trading, false sends Alerts input bool SendMailMode = false; // If ON (true), sends mail with order execution info input bool PlaySounds = false; // If ON (true), Plays a sound when orders/alarms are executed input string MySound="alert.wav"; // Sound to be played when orders/alarms are executed //5 digits management input bool FiveDigits = true; //if false, broker uses 4 digits int PipMultiplier = 1; // to multiply positions by 10 when 5 digits is true // Trading Variables input bool UseTradingTime = false; // If ON (true), trades only when tradingtimestart1 then a trade is opened every time there is a signal (buy or sell) input int MaxOrderRetry = 10; // if there is an error executing orders, the script retries MaxOrderRetry times // Money Management Variables input bool UseMaximumPercentageatRisk = false; // Turns on/off max risk condition input double MaximumPercentageatRisk = 1; // i.e max size of trade = 2 = 2% of equity input bool UseLotManagement = false; // Turns on/off lot management input int LotManagementType = 2; // 1 - Uses Decrease factor // 2 - Uses a fix factor 75%,50%,25% input double ReductionFactor = 5; // for money management lot-(lot*losses/ReductionFactor) input double DecreaseLotAfterLoss = 2; // For lot management 1, it waits until DecreaseLotAfterLoss consecutive loses to reduce lot size // Variables available in MT5 and not in the builder input int Slippage = 3; // Minimum slippage accepted int _Slippage = 3; // internal variable to store slippage // TP/SL/TS/LS backtesting variables //Values in pips. 10=10 pips. input double S_Symbol_LS_0 = 0.1; //Used to change value or backtest Lot Size input double S_Symbol_TP_0 = 30; //Used to change value or backtest Take Profit input double S_Symbol_SL_0 = 30; //Used to change value or backtest Stop Loss input double S_Symbol_TS_0 = 0; //Used to change value or backtest Trailing Stop input double B_Symbol_LS_0 = 0.1; //Used to change value or backtest Lot Size input double B_Symbol_TP_0 = 30; //Used to change value or backtest Take Profit input double B_Symbol_SL_0 = 30; //Used to change value or backtest Stop Loss input double B_Symbol_TS_0 = 0; //Used to change value or backtest Trailing Stop // Used to keep global variables input int MagicNumberLong = 6658641; //Identifies long positions input int MagicNumberShort = 4167090; //Identifies short positions input bool ShowWarnings=true; //Set to false if you do not want warnings/alerts string commentlong="Go long "; //Identifies long positions string commentshort="Go short "; //Identifies short positions int PreviousBarCount = 0; // To count bars int ObjCount = 0; // To count arrows string mailstring = ""; // string to store mail body string subject = "EA: "; // string to store mail subject double High[],Low[],Open[],Close[]; //To manage prices //Indicator Handle int iMA_L1; int iMA_R1; int iMA_L2; int iMA_R2; int iMA_L3; int iMA_R3; int iMA_L4; int iMA_R4; int iMA_L5; int iMA_R5; int iMA_L6; int iMA_R6; //Indicator Arrays double iMA_L1_Value[]; double iMA_R1_Value[]; double iMA_L2_Value[]; double iMA_R2_Value[]; double iMA_L3_Value[]; double iMA_R3_Value[]; double iMA_L4_Value[]; double iMA_R4_Value[]; double iMA_L5_Value[]; double iMA_R5_Value[]; double iMA_L6_Value[]; double iMA_R6_Value[]; string a43="Activ"; string a33="Error 27 - Please contact xxxx"; //+------------------------------------------------------------------+ //| MT5 functions | //+------------------------------------------------------------------+ #include #include #include #include #include #include //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ //The initialization function OnInit() contains instructions that run only once, run before any other //code in the Expert Advisor. The main purpose of this section is to initialize variables. void OnInit() { string a32=AccountInfoString(ACCOUNT_COMPANY); if (StringSubstr(a32,0,5)!=a43) { Print(a33); MessageBox(a33,"xxxs"); return; } //Set transaction comment commentlong="Go long "+MagicNumberLong; //Identifies long positions commentshort="Go short "+MagicNumberShort; //Identifies short positions //Reset Objects that paint arrows ObjectsDeleteAll(0,0,OBJ_ARROW_BUY); ObjectsDeleteAll(0,0,OBJ_ARROW_SELL); ObjCount = 0; // Check account type and mode Print("M-",_Symbol," *** EA created with Expert Advisor Visual Wizard 3.1 *** "); Print("Broker =",AccountInfoString(ACCOUNT_COMPANY)); Print("Deposit currency =",AccountInfoString(ACCOUNT_CURRENCY)); Print("Trade server =",AccountInfoString(ACCOUNT_SERVER)); Print("M-",_Symbol," *** EA starts running at: Server Time=",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS)," Terminal Time=",TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS)); if (AccountInfoInteger(ACCOUNT_TRADE_MODE) == ACCOUNT_TRADE_MODE_DEMO) { Print("M-",_Symbol," *** Running in a DEMO account *** "); } if (AccountInfoInteger(ACCOUNT_TRADE_MODE) == ACCOUNT_TRADE_MODE_REAL) { Print("M-",_Symbol," *** Running in a REAL account *** "); } if (MQL5InfoInteger(MQL5_TESTING)) { Print("M-",_Symbol," *** Running in TESTING MODE *** "); } Print("M-Account Equity=",AccountInfoDouble(ACCOUNT_EQUITY),". Account Balance=",AccountInfoDouble(ACCOUNT_BALANCE),". Account Free Margin = ",AccountInfoDouble(ACCOUNT_FREEMARGIN),". Account Leverage=",AccountInfoInteger(ACCOUNT_LEVERAGE)); // Verify if there are open positions and alert if(PositionVolume(_Symbol)>0) { if (ShowWarnings) MessageBox("M-There are existing open positions for pair "+_Symbol+" Volume="+PositionVolume(_Symbol)+". Please make sure this is OK before trading with this EA. ","Warning - Open positions exists."); Print("M-There are existing open positions for pair ",_Symbol," Volume=",PositionVolume(_Symbol),". Please make sure this is OK before trading with this EA. "); } // Check for enough ticks and trade permission if(Bars(_Symbol,_Period)<100) { Print("M-",_Symbol," *** CAN NOT TRADE *** Not enough historical information!"); if (ShowWarnings)MessageBox("M-"+_Symbol+" *** CAN NOT TRADE *** Not enough historical information!","Warning"); } if(!MQL5InfoInteger(MQL5_TRADE_ALLOWED)) { Print("M-",_Symbol," *** CAN NOT TRADE *** Trading is not allowed! Please confirm that the checkbox -Allow Live Trading option- is checked and that you are able to connect to the server."); if (ShowWarnings) MessageBox("M-"+_Symbol+" *** CAN NOT TRADE *** Trading is not allowed! Please confirm that the checkbox -Allow Live Trading option- is checked and that you are able to connect to the server.","Warning"); } //Using current symbol to check for account type Print("M-Lot Information: Symbol=",_Symbol,". MIN LOT ALLOWED=",SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN),". MAX LOT ALLOWED=",SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX),". LOT SIZE IN BASE CURRENCY=",SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE)); Print("M-Lot Information: Buying 1 lot in your Account is equivalent to buying ",SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE)," of currency."); Print("M-Lot Information: Buying the minimum lot size of ",SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN)," is equivalent to buying ",SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE)*SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN)," of currency."); //Adjust calculations for 5 digit brokers if (FiveDigits) { PipMultiplier = 10; } _Slippage = Slippage*PipMultiplier; if( (_Digits==5 || _Digits==3) && (!FiveDigits) ) { Print("M-",_Symbol," You selected FiveDigits=False but your graph seems to have 5 digits (or 3 for JPY pairs). Please review your digits definition."); if (ShowWarnings) MessageBox("M-"+_Symbol+" You selected FiveDigits=False but your graph seems to have 5 digits (or 3 for JPY pairs). Please review your digits definitions.","Digits setup may be wrong"); } if( (_Digits==4 || _Digits==2) && (FiveDigits) ) { Print("M-",_Symbol," You selected FiveDigits=True but your graph seems to have 4 digits (or 2 for JPY pairs). Please review your digits definition."); if (ShowWarnings) MessageBox("M-"+_Symbol+" You selected FiveDigits=True but your graph seems to have 4 digits (or 2 for JPY pairs). Please review your digits definitions.","Digits setup may be wrong"); } //Indicator Handle Get Value iMA_L1=iMA(xxx) if (iMA_L1 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_R1=iMA(xxx); if (iMA_R1 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_L2=iMA(xxx); if (iMA_L2 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_R2=iMA(xxx); if (iMA_R2 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_L3=iMA(xxx); if (iMA_L3 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_R3=iMA(xxx); if (iMA_R3 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_L4=iMA(xxx); if (iMA_L4 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_R4=iMA(xxx); if (iMA_R4 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_L5=iMA(xxx); if (iMA_L5 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_R5=iMA(xxx); if (iMA_R5 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_L6=iMA(xxx); if (iMA_L6 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } iMA_R6=iMA(xxx); if (iMA_R6 < 0) { Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!! Restart your EA again."); } //Indicator Set as Series ArraySetAsSeries(iMA_L1_Value, true); ArraySetAsSeries(iMA_R1_Value, true); ArraySetAsSeries(iMA_L2_Value, true); ArraySetAsSeries(iMA_R2_Value, true); ArraySetAsSeries(iMA_L3_Value, true); ArraySetAsSeries(iMA_R3_Value, true); ArraySetAsSeries(iMA_L4_Value, true); ArraySetAsSeries(iMA_R4_Value, true); ArraySetAsSeries(iMA_L5_Value, true); ArraySetAsSeries(iMA_R5_Value, true); ArraySetAsSeries(iMA_L6_Value, true); ArraySetAsSeries(iMA_R6_Value, true); //--- return; } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ //The deinitialization function contains instructions that run only once, run after all //the code on the expert advisor has been executed. The main purpose of this section is //to deinitialize/delete variables. void OnDeinit(const int reason) { Print("M-",_Symbol," EA deinit"); Print(__FUNCTION__,"_Uninitalization reason code =",reason); Print(__FUNCTION__,"_UninitReason =",getUnitReasonText(_UninitReason)); Comment(""); //Delete arrows ObjectsDeleteAll(0,0,OBJ_ARROW_BUY); ObjectsDeleteAll(0,0,OBJ_ARROW_SELL); //Indicator Release IndicatorRelease(iMA_L1); IndicatorRelease(iMA_R1); IndicatorRelease(iMA_L2); IndicatorRelease(iMA_R2); IndicatorRelease(iMA_L3); IndicatorRelease(iMA_R3); IndicatorRelease(iMA_L4); IndicatorRelease(iMA_R4); IndicatorRelease(iMA_L5); IndicatorRelease(iMA_R5); IndicatorRelease(iMA_L6); IndicatorRelease(iMA_R6); //--- } //+------------------------------------------------------------------+ //| expert OnTick function | //+------------------------------------------------------------------+ //The OnTick function contains instructions that run every time a tick is received. //This section is the main part of the expert advisor. void OnTick() { //--- string a32=AccountInfoString(ACCOUNT_COMPANY); if (StringSubstr(a32,0,5)!=a43) { Print(a33); MessageBox(a33,"ActivTrades"); return; } //Prepare trading flag bool CanTrade = true; //Prepare comment string mycomment; mycomment="This EA was created with Expert Advisor Visual Wizard v3.1 \n"; mycomment=""; if (TradeOrAlert) { mycomment=mycomment+" Trading Mode ON-"; } else { mycomment=mycomment+" Alarm Mode ON-"; } // Check trading time MqlDateTime mdt; TimeCurrent(mdt); // Check trading time if (UseTradingTime) { if (!(mdt.hour>=TradingTimeStart && mdt.hour<=TradingTimeEnd)) { StringConcatenate(mycomment," Server Time=",mdt.hour,"h:",mdt.min,"m. | Current server time is NOT between trading time hours. | Trading Time is from ",TradingTimeStart," to ",TradingTimeEnd," hours"); Comment(mycomment); CanTrade = false; return; } else { StringConcatenate(mycomment," Server Time=",mdt.hour,"h:",mdt.min,"m. | Current server time is between trading time hours. | Trading Time is from ",TradingTimeStart," to ",TradingTimeEnd, " hours"); Comment(mycomment); } } // Define string for email if (SendMailMode) { subject = "EA: "; StringConcatenate(subject,EAName," "); 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"); } // Check if trading is possible if(IsStopped()) { Print("M-",_Symbol," ERROR : EA was commanded to stop its operation!"); if (ShowWarnings) Alert("M-"+_Symbol+" ERROR : EA was commanded to stop its operation!"); if (SendMailMode) { StringConcatenate(subject,"EA was commanded to stop its operation",""); StringConcatenate(mailstring, "EA was commanded to stop its operation!\n",""); SendMail(subject, mailstring); } return; } if (!MQL5InfoInteger(MQL5_TRADE_ALLOWED) && TradeOrAlert && !CompletedBars) { Print("M-",_Symbol," ERROR : Trading is not allowed for this tick! Do not panic! This is an issue if it happens too many times in a row. Otherwise disregard this warning."); if (ShowWarnings) Alert("M-"+_Symbol+" ERROR : Trading is not allowed for this tick! Do not panic! This is an issue if it happens too many times in a row. Otherwise disregard this warning."); if (SendMailMode) { StringConcatenate(subject,"Trading is not allowed",""); StringConcatenate(mailstring, "Trading is not allowed for this tick! Do not panic! This is an issue if it happens too many times in a row. Otherwise disregard this warning.\n",""); SendMail(subject, mailstring); } CanTrade = false; return; } // Check for completed bars if CompletedBars mode is on if ((PreviousBarCount==Bars(_Symbol,PERIOD_CURRENT) && CompletedBars)) { CanTrade = false; //There are no new bars so do not trade } //Indicator CopyBuffer if ( CopyBuffer(iMA_L1,0,0,1,iMA_L1_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_R1,0,0,1,iMA_R1_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_L2,0,0,1,iMA_L2_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_R2,0,0,1,iMA_R2_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_L3,0,0,1,iMA_L3_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_R3,0,0,1,iMA_R3_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_L4,0,0,1,iMA_L4_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_R4,0,0,1,iMA_R4_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_L5,0,1,1,iMA_L5_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_R5,0,1,1,iMA_R5_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_L6,0,1,1,iMA_L6_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } if ( CopyBuffer(iMA_R6,0,1,1,iMA_R6_Value)!=1 ) { if (ShowWarnings) Alert("Error Copying indicator buffer - error: ",GetLastError(),"!! EA won't trade this tick or bar."); return; } // Trading code starts here if (CanTrade) { if (TradeOrAlert) { // Check trading conditions if ( (iMA_L6_Value[0] > iMA_R6_Value[0]) && (iMA_L4_Value[0] < iMA_R4_Value[0]) && (iMA_L3_Value[0] < iMA_R3_Value[0]) ) { SELL(Symbol(),S_Symbol_LS_0,S_Symbol_TP_0,S_Symbol_SL_0,S_Symbol_TS_0,"if ( (iMA_L6_Value[0] > iMA_R6_Value[0]) && (iMA_L4_Value[0] < iMA_R4_Value[0]) && (iMA_L3_Value[0] < iMA_R3_Value[0]) )") ;} if ( (iMA_L5_Value[0] < iMA_R5_Value[0]) && (iMA_L2_Value[0] > iMA_R2_Value[0]) && (iMA_L1_Value[0] > iMA_R1_Value[0]) ) { BUY(Symbol(),B_Symbol_LS_0,B_Symbol_TP_0,B_Symbol_SL_0,B_Symbol_TS_0,"if ( (iMA_L5_Value[0] < iMA_R5_Value[0]) && (iMA_L2_Value[0] > iMA_R2_Value[0]) && (iMA_L1_Value[0] > iMA_R1_Value[0]) )") ;} // Check Trailing stops CheckTrailingStop(Symbol(),POSITION_TYPE_SELL,MagicNumberShort,S_Symbol_TS_0); CheckTrailingStop(Symbol(),POSITION_TYPE_BUY,MagicNumberLong,B_Symbol_TS_0); } else { // Alerts if ( (iMA_L6_Value[0] > iMA_R6_Value[0]) && (iMA_L4_Value[0] < iMA_R4_Value[0]) && (iMA_L3_Value[0] < iMA_R3_Value[0]) ) { MolanisAlert("if ( (iMA_L6_Value[0] > iMA_R6_Value[0]) && (iMA_L4_Value[0] < iMA_R4_Value[0]) && (iMA_L3_Value[0] < iMA_R3_Value[0]) )","SELL(Symbol(),0.1,30,30,0)",Symbol()) ;} if ( (iMA_L5_Value[0] < iMA_R5_Value[0]) && (iMA_L2_Value[0] > iMA_R2_Value[0]) && (iMA_L1_Value[0] > iMA_R1_Value[0]) ) { MolanisAlert("if ( (iMA_L5_Value[0] < iMA_R5_Value[0]) && (iMA_L2_Value[0] > iMA_R2_Value[0]) && (iMA_L1_Value[0] > iMA_R1_Value[0]) )","BUY(Symbol(),0.1,30,30,0)",Symbol()) ;} } //trading code ends here } // Count bars PreviousBarCount=Bars(_Symbol,PERIOD_CURRENT); // To keep bar counter //return; } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| expert functions | //+------------------------------------------------------------------+ //// DO NOT DELETE THIS HEADER // DELETING THIS HEADER IS COPYRIGHT INFRIGMENT // Copyright © 2010, Molanis // YOU HAVE THE RIGHT TO PROFIT FROM ANY EA YOU CREATE WITH THIS SOFTWARE. HOWEVER, // SELLING ANY OF THE FOLLOWING FUNCTIONS SEPARATELY OR AS A TEMPLATE IS COPYRIGHT INFRIGMENT. // MOLANIS OWNS THE COPYRIGHT OF THE FOLLOWING FUNCTIONS AND AUTHORIZES YOU (A COMMERCIAL CLIENT) TO USE THEM AND SELL THEM // AS PART OF YOUR COMMERCIAL EA. MOLANIS WILL NOT ASK FOR ANY MONETARY RETRIBUTION BUT ASK YOU TO KEEP ALL MOLANIS REFERENCES // AND COPYRIGHT //The expert function section contains all functions of the expert advisor. //----functions start //MolanisAlert shows alerts and send emails (if SendMailMode is ON) with alerts /* *** Generated with Expert Advisor Visual Wizard 3.1 *** *** www.molanis.com *** *** Released 2010-06-20 *** */ int MolanisAlert(string condition, string sygnaltype, string mypair) { if (SendMailMode) { double mybid=SymbolInfoDouble(mypair,SYMBOL_BID); double myask=SymbolInfoDouble(mypair,SYMBOL_ASK); subject = "EA Alert: "; StringConcatenate(subject,EAName,". ",sygnaltype); 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, "Alert: ",sygnaltype,"\nForex Signal: ",condition,"\n"); StringConcatenate(mailstring, "Price on : ", mypair," BID=",mybid," ASK=",myask,"\n"); StringConcatenate(mailstring, "Price on current chart: ", Symbol()," BID=",SymbolInfoDouble(_Symbol,SYMBOL_BID)," ASK=",SymbolInfoDouble(_Symbol,SYMBOL_ASK),"\n"); SendMail(subject, mailstring); } // Print and show alert Print("Alert:",sygnaltype," Forex Signal: ",condition); Alert("Alert:",sygnaltype," Forex Signal: ",condition); if (PlaySounds) { PlaySound(MySound); } return(0); } //BUY opens a long position /* *** Generated with Expert Advisor Visual Wizard 3.1 *** *** www.molanis.com *** *** Released 2010-06-20 *** */ int BUY(string symbol_b, double lotsize_b, double takeprofit_b, double stoploss_b, double trailings_b, string condition_b) { //if conditions are true then open long position //close shorts and go long ClosePosition(symbol_b, POSITION_TYPE_SELL,MagicNumberShort); Sleep(SleepTime); if (ExecuteOrder(ORDER_TYPE_BUY, symbol_b, LotManagement(symbol_b,lotsize_b), !OrderIncludeTPSL, stoploss_b, takeprofit_b, commentlong, MagicNumberLong, condition_b)>0) { //Executed - Insert code here if needed } else { //Failure - Insert code here if needed } return(0); } //SELL opens a short position /* *** Generated with Expert Advisor Visual Wizard 3.1 *** *** www.molanis.com *** *** Released 2010-06-20 *** */ int SELL(string symbol_s, double lotsize_s, double takeprofit_s, double stoploss_s, double trailings_s, string condition_s) { //if conditions are true then open short position //close longs and go short ClosePosition(symbol_s,POSITION_TYPE_BUY,MagicNumberLong); Sleep(SleepTime); if (ExecuteOrder(ORDER_TYPE_SELL, symbol_s, LotManagement(symbol_s,lotsize_s), !OrderIncludeTPSL, stoploss_s, takeprofit_s, commentshort, MagicNumberShort, condition_s)>0) { //Executed - Insert code here if needed } else { //Failure - Insert code here if needed } return(0); } //ClosePosition closes open positions /* *** Generated with Expert Advisor Visual Wizard 3.1 *** *** www.molanis.com *** *** Released 2010-06-20 *** */ int ClosePosition(string symbolclose, ENUM_POSITION_TYPE posType, int magicclose) { if(posType != POSITION_TYPE_BUY && posType != POSITION_TYPE_SELL) { Print("M-",_Symbol,"Closing all positions failed. Order type is wrong."); if (ShowWarnings) Alert("M-",_Symbol,"Closing all positions failed. Order type is wrong."); return(-1); } CPositionInfo posInfo; CSymbolInfo symInfo; CTrade trade; symInfo.Name(symbolclose); if (posInfo.Select(symbolclose)) if (posInfo.PositionType() == posType && (posInfo.Magic() == magicclose || posInfo.Magic() == 0)) { int tries = 0; if (!isTradingPossible()) Print("M-",_Symbol," Warning: Trading may not be possible. Trying to close orders."); while (tries < MaxOrderRetry) { double vol = posInfo.Volume(), profit = posInfo.Profit(), openPrice = posInfo.PriceOpen(), price = posInfo.PriceCurrent(); if (trade.PositionClose(posInfo.Symbol(), _Slippage)) { Print("M-",_Symbol," Position Closed. Symbol:",symbolclose,". Lots:", vol, " Profit:", profit, " Open price=",DoubleToString(openPrice,symInfo.Digits())," Current price=",DoubleToString(price,symInfo.Digits())); 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,". ",symbolclose," ",PositionTypetoString(posType)," position was closed. "); 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 Closed\nOrder Info : \n Order Closed Type=", PositionTypetoString(posType), ".\n Symbol=", symbolclose, ".\n Lot Size=", vol, ".\n Closed at price:",price,".\n Position was opened at price:",openPrice,".\n Profit:",profit); SendMail(subject, mailstring); } return (0); } else { tries++; int err=trade.ResultRetcode(); string msg=""; StringConcatenate(msg,"M-",_Symbol," Closing Order failed. Symbol:",symbolclose,". Lots:",vol,". Error:",err," ", trade.ResultRetcodeDescription()," ",ErrorCodeDescription(trade.ResultRetcodeDescription())); Print("M-",_Symbol, " ",msg); if (ShowWarnings) Alert("M-"+_Symbol +" "+msg); if (SendMailMode) { //Prepare email subject = "EA: "; StringConcatenate(subject,EAName," WARNING:",symbolclose," ",PositionTypetoString(posType)," position could NOT be closed"); mailstring = "email SuperEA \n"; StringConcatenate(mailstring, "Server Time=",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),". Terminal Time=",TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS),"\n"); StringConcatenate(mailstring, "M-Closing Order failed.\nSymbol:",symbolclose,".\n Lots:",vol,".\n Error:",err,"\n", trade.ResultRetcodeDescription()); SendMail(subject, mailstring); } Sleep(SleepTime); } } Print("M-",_Symbol," Stopping Closing all positions. Too many errors when closing positions. Symbol:",symbolclose); Print("M-",_Symbol," URGENT:Please verify your Internet Connection and Server response."); if (ShowWarnings) Alert("M-"+_Symbol+" Stopping Closing all positions. Too many errors when closing positions. Symbol:",symbolclose); if (ShowWarnings) Alert("M-"+_Symbol+" URGENT:Please verify your Internet Connection and Server response."); } return(-1); } //EnoughMoney checks whether there is enough money to open the position. Returns False when there is no money to trade /* *** Generated with Expert Advisor Visual Wizard 3.1 *** *** www.molanis.com *** *** Released 2010-06-20 *** */ bool EnoughMoney(string symbol_em, double lotsize_em, double price_em) { CAccountInfo cacc; if(cacc.FreeMarginCheck(symbol_em,ORDER_TYPE_BUY,lotsize_em,price_em) < 10 || cacc.FreeMarginCheck(symbol_em,ORDER_TYPE_SELL,lotsize_em,price_em) < 10) { Print("M-",_Symbol," NOT ENOUGH MONEY TO TRADE. Free margin is insufficient to trade a lot size of ",lotsize_em,". Current Free Margin=", cacc.FreeMargin()); if (ShowWarnings) Alert("M-"+_Symbol+" NOT ENOUGH MONEY TO TRADE. Free margin is insufficient to trade a lot size of ",lotsize_em,". Current Free Margin=", cacc.FreeMargin()); return(false); } else { return(true); } } //ExecuteOrder opens a new position /* *** Generated with Expert Advisor Visual Wizard 3.1 *** *** www.molanis.com *** *** Released 2010-06-20 *** */ bool ExecuteOrder(ENUM_ORDER_TYPE ordertype_bn, string symbol_bn, double lotsize_bn, const bool ecn, double stoploss_bn, double takeprofit_bn, string comment_bn, int magic_bn, string condition_bn) { int digits_bn; int errorcode_bn; double PosVol; bool golong_bn; double points_bn; double price_bn; double fillprice_bn; CTrade trade; CSymbolInfo symInfo; CPositionInfo posInfo; symInfo.Name(symbol_bn); //fix decimal movement stoploss_bn=stoploss_bn*PipMultiplier; takeprofit_bn=takeprofit_bn*PipMultiplier; //Verify stops and alerts if(takeprofit_bn0) { Print("M-",_Symbol," Error: Take Profit must be greater than ",DoubleToString(symInfo.StopsLevel(),symInfo.Digits())," Please change your take profit in the EA properties before running this EA in a real account"); if (ShowWarnings) Alert("M-"+_Symbol+ " Error: Take Profit must be greater than "+DoubleToString(symInfo.StopsLevel(),symInfo.Digits())+" Please change your take profit in the EA properties before running this EA in a real account"); } ENUM_POSITION_TYPE pType; //Set ordertype boolean switch (ordertype_bn) { case ORDER_TYPE_BUY: pType = POSITION_TYPE_BUY; golong_bn=true; break; case ORDER_TYPE_SELL: pType = POSITION_TYPE_SELL; golong_bn=false; break; default: Print("M-",_Symbol," ERROR : Wrong order type ", ordertype_bn); return(-1); break; } // Check if there is enough money to close the position symInfo.RefreshRates(); //Gets pair info to prepare price digits_bn = symInfo.Digits(); points_bn = symInfo.Point(); //adjust lot int tmpdecimal=1; if (IsMicroAccount) { tmpdecimal=2; } double old_lot=lotsize_bn; if ((NormalizeDouble(AccountInfoDouble(ACCOUNT_FREEMARGIN)*(MaximumPercentageatRisk/100)/1000.0,tmpdecimal)1.0E-10) { lotsize_bn=SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_STEP)*NormalizeDouble(lotsize_bn/SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_STEP),0); Print("M-",_Symbol," Warning: Your calculated percentage at risk lot size of was not a multiple of minimal step",SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_STEP),". Lot size changed to",lotsize_bn); } } } //check previous deals / volumen PosVol=PositionVolume(symbol_bn); if (PosVol==0) { Sleep(SleepTime); PosVol=PositionVolume(symbol_bn); if (PosVol==0) { Sleep(SleepTime); PosVol=PositionVolume(symbol_bn); } } Print(symbol_bn," volume=",PosVol," lotsize=",lotsize_bn," sum=",PosVol+lotsize_bn, " maxlotsize=",MaxVolumePosition); if ( NormalizeDouble( (PosVol+lotsize_bn),3 ) > NormalizeDouble(MaxVolumePosition,3) ) { if (ShowWarnings) Print("M-",_Symbol," Warning : Can not execute new order for ",PositionTypetoString(pType)," for Symbol ",symbol_bn,". Maximum Volume ", MaxVolumePosition," reached."); return(-1); } // go long set up if (golong_bn) { price_bn = symInfo.Ask(); } else { price_bn = symInfo.Bid(); } if (!EnoughMoney(symbol_bn, lotsize_bn,price_bn)) { Print("M-",_Symbol," Error: Not enough money to open position!"); if (ShowWarnings) Alert("M-"+_Symbol+" Error: Not enough money to open position!"); return(-1); } int tries = 1; bool ecnOpened = false; while(tries>0) { symInfo.RefreshRates(); // go long set up if (golong_bn) { price_bn = symInfo.Ask(); if (stoploss_bn > 0) { //Verify stop loss if valid stoploss_bn = NormalizeDouble(price_bn-stoploss_bn*points_bn, digits_bn); //stoploss_bn = CheckStopLoss(symbol_bn, price_bn, stoploss_bn); } if (takeprofit_bn > 0) { //Verify take profit is valid takeprofit_bn= NormalizeDouble(price_bn+takeprofit_bn*points_bn, digits_bn); //takeprofit_bn = CheckTakeProfit(symbol_bn, price_bn, takeprofit_bn); } Print("M-",_Symbol," Prepare BUY order ",symbol_bn," Buy Order.Price : Ask = ",DoubleToString(price_bn,digits_bn),". Stoploss = ",DoubleToString(stoploss_bn,digits_bn),". Takeprofit = ",DoubleToString(takeprofit_bn,digits_bn)," Lotsize=",DoubleToString(lotsize_bn,digits_bn)); Print("M-",_Symbol," triggered by ",condition_bn); } else { // go short set up price_bn = symInfo.Bid(); if (stoploss_bn > 0) { //Verify stop loss is valid stoploss_bn = NormalizeDouble(price_bn+stoploss_bn*points_bn, digits_bn); //stoploss_bn = CheckStopLoss(symbol_bn, price_bn, stoploss_bn); } if (takeprofit_bn>0) { //Verify take profit are valid takeprofit_bn= NormalizeDouble(price_bn-takeprofit_bn*points_bn, digits_bn); //takeprofit_bn = CheckTakeProfit(symbol_bn, price_bn, takeprofit_bn); } Print("M-",_Symbol," Prepare SELL order ",symbol_bn," Sell Order.Price : Bid = ",DoubleToString(price_bn,digits_bn),". Stoploss = ",DoubleToString(stoploss_bn,digits_bn),". Takeprofit = ",DoubleToString(takeprofit_bn,digits_bn)," Lotsize=",DoubleToString(lotsize_bn,digits_bn)); Print("M-",_Symbol," triggered by ",condition_bn); } // Verify order execution if (!isTradingPossible()) { Print("M-",_Symbol," Warning: Trading may not be possible. Trying to open a new position."); } trade.SetExpertMagicNumber(magic_bn); trade.SetDeviationInPoints(_Slippage); bool success = false; success = trade.PositionOpen(symbol_bn,ordertype_bn,lotsize_bn,price_bn,stoploss_bn,takeprofit_bn,comment_bn); errorcode_bn = trade.ResultRetcode(); if(success && (errorcode_bn==TRADE_RETCODE_PLACED || errorcode_bn==TRADE_RETCODE_DONE) ) { 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 (lotSymbolInfoDouble(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 (lotSymbolInfoDouble(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 (lotSymbolInfoDouble(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 (lotSymbolInfoDouble(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 (lotSymbolInfoDouble(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*PipMultiplier0) { 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 && index0 && index0 && index0 && index iMA_R6_Value[0]) && (iMA_L4_Value[0] < iMA_R4_Value[0]) && (iMA_L3_Value[0] < iMA_R3_Value[0]) ) { SELL(Symbol(),S_Symbol_LS_0,S_Symbol_TP_0,S_Symbol_SL_0,S_Symbol_TS_0,"if ( (iMA_L6_Value[0] > iMA_R6_Value[0]) && (iMA_L4_Value[0] < iMA_R4_Value[0]) && (iMA_L3_Value[0] < iMA_R3_Value[0]) )") ;} if ( (iMA_L5_Value[0] < iMA_R5_Value[0]) && (iMA_L2_Value[0] > iMA_R2_Value[0]) && (iMA_L1_Value[0] > iMA_R1_Value[0]) ) { BUY(Symbol(),B_Symbol_LS_0,B_Symbol_TP_0,B_Symbol_SL_0,B_Symbol_TS_0,"if ( (iMA_L5_Value[0] < iMA_R5_Value[0]) && (iMA_L2_Value[0] > iMA_R2_Value[0]) && (iMA_L1_Value[0] > iMA_R1_Value[0]) )") ;} //Alerts if ( (iMA_L6_Value[0] > iMA_R6_Value[0]) && (iMA_L4_Value[0] < iMA_R4_Value[0]) && (iMA_L3_Value[0] < iMA_R3_Value[0]) ) { MolanisAlert("if ( (iMA_L6_Value[0] > iMA_R6_Value[0]) && (iMA_L4_Value[0] < iMA_R4_Value[0]) && (iMA_L3_Value[0] < iMA_R3_Value[0]) )","SELL(Symbol(),0.1,30,30,0)",Symbol()) ;} if ( (iMA_L5_Value[0] < iMA_R5_Value[0]) && (iMA_L2_Value[0] > iMA_R2_Value[0]) && (iMA_L1_Value[0] > iMA_R1_Value[0]) ) { MolanisAlert("if ( (iMA_L5_Value[0] < iMA_R5_Value[0]) && (iMA_L2_Value[0] > iMA_R2_Value[0]) && (iMA_L1_Value[0] > iMA_R1_Value[0]) )","BUY(Symbol(),0.1,30,30,0)",Symbol()) ;} */