Close positions or reduce losses by target - MetaTrader 4 Expert | MT4 EA Download - MetaTrader 4 Resources
3 inputs are required, as follows:
External double inTargetProfitMoney = 10 ; //Target profit ($) External double inCutLossMoney = 0.0 ; //Stop loss ($) External integer inMagicNumber = 0 ; //magic number
When this EA is executed, it will first call the OnInit () function. where we will validate input and variable initialization
Integer initialization () { //--- if (inTargetProfitMoney <= 0 ) { alert ( "invalid input" ); return ( INIT_PARAMETERS_INCORRECT ); } Loss reduction funds = mathematical antibody (based on loss reduction amount) * - 1 ; //--- return ( initialization successful ); }
And the OnTick() function will be called every time the price changes (tick)
Blank check () { //--- Double t float = 0.0 ; Integer t order = total number of orders (); order ( integer i=t order - 1 ; i >= 0 ; i -) { if ( order select (i, select by POS, MODE_TRADES)) { if (OrderMagicNumber() == inMagicNumber) { tFloating += OrderProfit()+OrderCommission() + OrderSwap(); } } } if (tFloating >= inTargetProfitMoney || (tFloating <= inCutLossMoney && inCutLossMoney < 0 )) { fCloseAllOrders(); } }
In the OnTick function, the total profit or loss will continue to be calculated. All orders that can fulfill the target or maximum loss limit will then be closed
Blank f closes all orders() { Double closing price = 0.0 ; Integer t order = total number of orders (); order ( integer i=t order - 1 ; i >= 0 ; i -) { if ( order select (i, select by POS, MODE_TRADES)) { if (OrderMagicNumber() == inMagicNumber && (OrderType() == OP_BUY || OrderType() == OP_SELL)) { PriceClose = (OrderType()==OP_BUY)?MarketInfo(OrderSymbol(), MODE_BID):MarketInfo(OrderSymbol(), MODE_ASK); if (!OrderClose(OrderTicket(), OrderLots(), priceClose, slippage, gold )) { print ( "Warning: Close failed" ); } } } } }
If you want to know more details and sharing about MQL4 code education, please join our Telegram groupt.me/codeMQL
Attachment download
📎 closeorders.mq4 (3.47 KB)
Source: MQL5 #34194
💡 Featured Recommendations
✍️ Latest by the author
- •
- •
- •
- •
- •
- •
📌 Popular topics
- •
- •
- •
- •
- •
- •
- •
- •
🔗 You May Be Interested In
- •
- •
- •
- •
- •
- •