Lazy Bot MT5 (Daily Breakout EA) - MetaTrader 5 Expert - MetaTrader 5 Resources
//Import external class #include <Trade\PositionInfo.mqh> #include <Trade\Trade.mqh> #include <Trade\SymbolInfo.mqh> #include <Trade\AccountInfo.mqh> #include <Trade\OrderInfo.mqh> //--- Introduce predefined variables to improve code readability #define ask symbol information double ( _symbol , SYMBOL_ASK ) #define bid symbol information double ( _symbol , SYMBOL_BID ) //--- Input parameters Input string EA settings = "——————————————————" ; //---------------- Input integer InpMagicNumber = 123456 ; //magic number Input string InpBot name = "LazyBot_V1" ; //robot name Enter string trade settings = "——————————————————" ; //-------- <trade settings> -------- Enter double Enter the user's lot size = 0.01 ; //A lot Enter double Enter user_SL = 5.0 ; // Stop loss (in pips) Enter double InpAddPrice_pip = 0 ; //Distance from [H], [L] to OP_Price (in points) Input integer input user_SLippage = 3 ; // Maximum slippage allow_Pips. Enter double InpMax_spread = 0 ; //Maximum spread allowed in pips (0 = float) Enter string time setting = "——————————————————" ; //-------- <Trading time setting> -------- Input boolean Trading time = true ; //Allow trading time Input integer Inp start time = 7 ; //Start time Input integer InpEndHour = 22 ; //End time Enter string Money Management Settings = "——————————————————" ; //-------- <Currency Settings> -------- Input boolean isVolume_Percent = false ; //Allow volume percentage Enter double the Inp risk = 1 ; //Balance risk percentage (%)
2. Initialization of local variables
//Local parameters Last date and time ; integer total number of bars; integer Pips2Points; // slippage 3 points 3=points 30=points Double points 2 pairs; // Stop loss 15 points 0.015 0.0150 Double the slip; Double the ac spread; string string comment = "" ; CPositionInfo m_position; // Trading position object CTrade m_trade; // Trading object CSymbolInfo m_symbol; // Trading type information object CAccountInfo m_account; // Account information packaging COrderInfo m_order; // Pending order object
3. Main code
Explaining the strategy, Everyday Bot will delete all old orders and find the highest and lowest values of the previous day's bar and send to two pending orders " Buy_StopLoss ", " Sell_StopLoss ". (No take profit).
a/ expert initialization function
Integer initialization () { //--- //3-digit or 5-digit detection // dot and dot if ( _digit % 2 == 1 ) { Pips2Double= _View * 10 ; Pips2Points = 10 ; Slippage = 10 * Inpuser_SLippage; } other { Pips2Double= _View ; Pips2Points = 1 ; slippage = Inpuser_SLippage; } if (!m_symbol.name( symbol ())) // Set the symbol name and return ( initialization failed ); Refresh rate(); //--- m_trade.SetExpertMagicNumber(InpMagicNumber); m_trade.SetMarginMode(); m_trade.SetTypeFillingBySymbol(m_symbol.Name()); m_trade.SetDeviationInPoints(slippage); //--- return ( initialization successful ); }
b/ Expert check function
Blank check () { if ( terminalinfo integer ( TERMINAL_TRADE_ALLOWED ) == false ) { Comment ( "LazyBot\nTrading is not allowed." ); return ; } //Get trading time, //Open section //London 14 hours - 23 hours GMT Vietnam // New York 19 hours - 04 hours GMT Vietnam Mql date time local time; Mql date time time server; timelocal (localtime); timecurrent (timeserver); // Does not work on holidays. if (timeServer.day_of_week == 0 || timeServer.day_of_week == 6 ) return ; integer hourLocal = timeLocal.hour; //TimeHour(TimeLocal()); integer current time = timeServer.hour; //time hour(TimeCurrent()); ac propagation = symbolinfo integer ( _symbol , symbol_propagation ); string comment = "\nlocal time = " + hour local; str comment += "\ncurrent time = " + hour current; str comment += "\nspread=" + ( thin string )acSpread; str comment += "\nTotal number = " + ( thin rope ) total number of pieces; Comment (strComment); //Check trailing trailing SL(); //--- if (last!=When in love(m_symbol.Name(), PERIOD_D1 , 0 )) // && current hour > InpStartHour) { //Check the transaction time if (is the transaction time) { if (current hour >= InpStartHour) // && current hour < InpEndHour){ { Delete old order(); //Send orders BUY_STOP and SELL_STOP open order(); Finally=When in love(m_symbol.Name(), PERIOD_D1 , 0 ); } } other { Delete old order(); //Send orders BUY_STOP and SELL_STOP open order(); Finally=When in love(m_symbol.Name(), PERIOD_D1 , 0 ); } } }
3.1 Calculate signals and send orders
//+------------------------------------------------------------------+ //|Calculate signals and send instructions | //+------------------------------------------------------------------+ Blank opening order() { Double TP_Buy= 0 , TP_Sell= 0 ; Double SL_Buy= 0 , SL_Sell= 0 ; //Check the maximum spread if (InpMax_spread != 0 ){ if (acSpread > InpMax_spread){ Print ( __Function__ , ">The current spread is greater than the user's spread!..." ); return ; } } Double Bar1High = m_symbol.NormalizePrice(love high(m_symbol.Name(), PERIOD_D1 , 1 )); Double Bar1Low = m_symbol.NormalizePrice( Low (m_symbol.Name(), PERIOD_D1 , 1 )); //Calculate the double lot size 1 = Calculate the trading volume(); Double OpenPrice = m_symbol.NormalizePrice(Bar1High + InpAddPrice_pip * Pips2Double); // + NormalizeDouble((acSpread/Pips2Points) * Pips2Double, Digits); //For BUY_STOP -------------------------------- TP_Buy = 0 ; //Bar1High + NormalizeDouble(min_sl* Pips2Double, Digits); SL_Buy = m_symbol.NormalizePrice(OpenPrice - Inpuser_SL * Pips2Double); Total number of bars = bar (m_symbol.Name(), PERIOD_D1 ); String comments = InpBotName + “;” + m_symbol.Name() + “;” + total number; if (check volume value(lot1) && CheckOrderForFREEZE_LEVEL( ORDER_TYPE_BUY_STOP , opening price) && CheckMoneyForTrade(m_symbol.Name(),lot1, order type purchase ) && Check Stop Loss(OpenPrice, SL_Buy)) { if (!m_trade.BuyStop(lot1, OpenPrice, m_symbol.Name(), SL_Buy, TP_Buy, ORDER_TIME_GTC , 0 , comment)) // Use "ORDER_TIME_GTC" when expiration date = 0 print ( __function__ , "-->Buy Error" ); } //For SELL_STOP -------------------------------- OpenPrice = m_symbol.NormalizePrice(Bar1Low - InpAddPrice_pip * Pips2Double); // - NormalizeDouble((acSpread/Pips2Points) * Pips2Double, Digits); TP_Sell = 0 ; //Bar1Low - NormalizeDouble(min_sl* Pips2Double, Digits); SL_Sell = m_symbol.NormalizePrice(OpenPrice + Inpuser_SL * Pips2Double); if (check volume value(lot1) && CheckOrderForFREEZE_LEVEL( ORDER_TYPE_SELL_STOP , opening price) && CheckMoneyForTrade(m_symbol.Name(),lot1, order type_sell ) && Check Stop Loss(OpenPrice, SL_Sell)) { if (!m_trade.SellStop(lot1, OpenPrice, m_symbol.Name(), SL_Sell, TP_Sell, ORDER_TIME_GTC , 0 , comments)) print ( __function__ , "-->Sales Error" ); } }
3.2 New day, delete all old orders
//+------------------------------------------------------------------+ //|Delete old orders | //+------------------------------------------------------------------+ Blank delete old order() { string sep = ";" ; // Delimiter as character ultrashort u_sep; // Delimiter code string result[]; // Get an array of strings in order ( integer i = total number of orders () - 1 ; i >= 0 ; i - ) // Return the current order quantity { if (m_order.SelectByIndex(i)) // Select pending order by index to further access its properties { //--- Get separator code u_sep = string getChar (September, 0 ); string order comment = m_order.comment (); //Split OrderComment(EAName;Symbol;totalBar) to get Ordersymbol integer k = string split (Ordcomment, u_sep, result); if (k> 2 ) { String sym = m_symbol.Name(); if ((m_order.Magic() == InpMagicNumber) && (sym == result[ 1 ])) { m_trade.OrderDelete(m_order.Ticket()); } } } } }
3.3 EA has a "trailing stop loss" function, SL will change every time the price changes, making profits increase
//+------------------------------------------------------------------+ //|Trailing Stop | //+------------------------------------------------------------------+ White space trailing SL() { Double SL_in_Pip = 0 ; For ( integer i = total number of positions () - 1 ; i >= 0 ; i -) { if (m_position.SelectByIndex(i)) // Select order by index to further access its properties { if ((m_position.Magic() == InpMagicNumber) && ( m_position.symbol () == m_symbol.Name())) //m_symbol.Name() { Double order_stoploss1 = m_position.StopLoss(); // For purchase orders if (m_position.PositionType() == POSITION_TYPE_BUY ) { //-- Calculate stop loss when price changes SL_in_Pip = normalized double ((bid - order_stoploss1), _number ) / Pips2Double; //Print(__FUNCTION__, "Modify order to buy" + (string)SL_in_Pip); if (SL_in_Pip > Inpuser_SL) { Order_Stop1 = Normalized Double (Bid - (Inpuser_SL * Pips2Double), _Number ); m_trade.PositionModify(m_position.Ticket(), order_stoploss1, m_position.TakeProfit()); } } //For sell orders if (m_position.PositionType() == POSITION_TYPE_SELL ) { //-- Calculate stop loss when price changes SL_in_Pip = Normalized Double ((m_position.StopLoss() - query), _number ) / Pips2Double; if (SL_in_Pip > Inpuser_SL) { Order_Stop1 = Normalized Double (Ask + (Inpuser_SL * Pips2Double), _Number ); m_trade.PositionModify(m_position.Ticket(), order_stoploss1, m_position.TakeProfit()); } } } } } }
3.4 Check volume value
//+------------------------------------------------------------------+ //|Check if the order quantity is correct| //+------------------------------------------------------------------+ Boolean check volume value ( double the volume) { //--- double the minimum allowed trading volume for trading operations min_volume = m_symbol.LotsMin(); //--- Double the maximum allowed transaction operation volume max_volume = m_symbol.LotsMax(); //--- Get double the minimum step size for volume change Volume_step = m_symbol.LotsStep(); if (volume < minimum volume || volume > maximum volume) { return ( false ); } integer ratio = ( integer ) mathwheel (volume/volume-step); if ( math antibody (ratio*volume_step_volume) > 0.0000001 ) { return ( false ); } return ( true ); }
3.5 Check the freedom level
//+------------------------------------------------------------------+ //|Check freeze level | //+------------------------------------------------------------------+ Boolean CheckOrderForFREEZE_LEVEL( ENUM_ORDER_TYPE type, double price) //Change the name of this function { integer freezelevel = ( integer ) symbolinfointeger ( _symbol , SYMBOL_TRADE_FREEZE_LEVEL ); booleancheck = false ; //--- Check only two order type transitions (types) { //--- Buy operation case ORDER_TYPE_BUY_STOP : { //--- Check the distance from the opening price to the activation price check = ((price-ask) > freeze_level* _view ); //--- Return the check result return (view); } //--- Sell operation case ORDER_TYPE_SELL_STOP : { //--- Check the distance from the opening price to the activation price check = ((bid)>freeze_level* _view ); //--- Return the check result return (view); } rest ; } //--- Pending orders require a slightly different function that returns an error ; }
3.6 Check transaction funds
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ Boolean check for transaction currency ( string symbol, double lot, ENUM_ORDER_TYPE type) { //--- Get the opening price MQTick MQLTICK; SymbolInformationCheck (symbol, MQLTICK); Double price=mqltick.ask; if (type== order_type_sell ) Price=mqltick.bid; //--- The value of required margin and available margin is double the margin, free_margin= account information double ( ACCOUNT_MARGIN_FREE ); //--- Call the check function if (! order calculation margin (type, symbol, lot, price, margin)) { //--- Something went wrong, report it and return false print ( "error in" , __function__ , "code=" , get the last error ()); return ( false ); } //--- if there are not enough funds to perform the operation if (margin > free margin) { //--- Report an error and return false to print ( "Not enough money" , enumeration to string (type), " " , many, " " , symbol, "error code = " , get the last error ()); return ( false ); } //--- check returns successfully ( true ); }
3.7 Check Stop Loss
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ boolean check stop loss ( double price, double SL) { //--- Get SYMBOL_TRADE_STOPS_LEVEL horizontal integer stop level = ( integer ) symbol information integer (m_symbol.Name(), SYMBOL_TRADE_STOPS_LEVEL ); if (stoplevel != 0 ) { Print format ( "SYMBOL_TRADE_STOPS_LEVEL=%d: Stop loss and profit must be set" + "Not more than %d points from the closing price" , stop level, stop level); } //--- boolean SL_CHECK = false ; //--- checkstops return SL_check = mathab (price - stoploss) > (stops_level * m_symbol.view ()); }
Video MQL4:
Attachment download
📎 lazybot_mt5_v1.mq5 (17.21 KB)
Source: MQL5 #41732
💡 Featured Recommendations
✍️ Latest by the author
- •
- •
- •
- •
- •
- •
📌 Popular topics
- •
- •
- •
- •
- •
- •
- •
- •
🔗 You May Be Interested In
- •
- •
- •
- •
- •
- •