If you’re tired of watching your trades bleed and want a safety net, this code is just what you need! It automates the process of closing all open trades when your drawdown hits a predetermined percentage of your account balance.
All you have to do is input the magic number of the trades you want to monitor (you can enter 0 to manage all your trades), and specify the maximum drawdown percentage that will trigger the closure of those trades.
To make this work, simply call the function DD_close in your EA.
I've also attached the header file for this code along with the EA built on it.
// To use this option, just call the function: ( DD_close ) //+------------------------------------------------------------------+ //| Global scope | //+------------------------------------------------------------------+ bool Close_All_V; //+------------------------------------------------------------------+ //| Main function | //+------------------------------------------------------------------+ // DD: This is the drawdown percentage, 100 means never close any order. // Magic_Number: Your EA magic number; enter 0 to manage all orders. void DD_close(int DD,int Magic_Number) { if(DD(Magic_Number)>=DD) Close_All_V=true; if(Close_All_V) Close_All(Magic_Number); } //+------------------------------------------------------------------+ //| Check close | //+------------------------------------------------------------------+ void Check_Close(int Check_Number) // check close order { if(Check_Number<0) Print("OrderClose failed with error: ",ErrorDescription(GetLastError())); else Close_All_V=false; } //+------------------------------------------------------------------+ //| Close all | //+------------------------------------------------------------------+ void Close_All(int M_N) { int Loop=0; for(int i=0; Loop<OrdersTotal(); i++) if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) { Loop++; if(OrderSymbol()==Symbol()) if(OrderMagicNumber()==M_N || OrderMagicNumber()==0) { if(OrderType()==OP_BUY) Check_Close(OrderClose(OrderTicket(),OrderLots(),Bid,100,clrNONE)); if(OrderType()==OP_SELL) Check_Close(OrderClose(OrderTicket(),OrderLots(),Ask,100,clrNONE)); } } } //+------------------------------------------------------------------+ //| Calculate loss | //+------------------------------------------------------------------+ double Loss(int M_N) { double re=0; int Loop=0; for(int i=0; Loop<OrdersTotal(); i++) if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) { Loop++; if(OrderSymbol()==Symbol()) if(OrderMagicNumber()==M_N || OrderMagicNumber()==0) re=re+OrderProfit(); } return re * -1; } //+------------------------------------------------------------------+ //| Calculate drawdown percentage | //+------------------------------------------------------------------+ double DD(int M_N) { return ( 100 / AccountBalance ( ) ) * Loss ( M_N ); } //+------------------------------------------------------------------+