TradeHedgeCLOSEALL_v5
Download scriptThis script is a specialized utility designed for MetaTrader 4 to provide a "hard reset" for your trading positions. Its primary purpose is to scan your active account and immediately close specific types of trades that meet certain criteria.
Core Functionality
The tool operates by scanning all currently open orders in your trading terminal. Rather than closing every single trade indiscriminately, it looks for a specific identification tag known as a Magic Number (specifically: 200809241653). This allows the script to target only the trades opened by a specific automated system or strategy while leaving your other manual trades or different automated tools untouched.
How It Works
When activated, the script follows a systematic process:
- Target Identification: It iterates through every open position in your account, backward from the most recent to the oldest.
- Filtered Execution: It checks each order against the predefined Magic Number. If a match is found, it identifies whether the position is a "Buy" or a "Sell."
- Automated Liquidation:
- For Buy positions, it attempts to close them at the current market price.
- For Sell positions, it attempts to close them at the current market price.
- Error Handling and Persistence: Trading environments can sometimes be volatile, leading to temporary execution errors (such as price gaps or connection flickers). To combat this, the script includes a "retry logic":
- If an order fails to close on the first try, the script waits for half a second and then attempts again.
- It repeats this process automatically until the trade is successfully closed or until it reaches a maximum retry limit.
- Alert System: If a trade persistently fails to close after multiple attempts, the script will trigger a visual alert on your screen and log a detailed error message in the journal so you can investigate any underlying issues.
Summary for the User
Essentially, this is an emergency "Off Switch" for a specific trading strategy. It ensures that all active positions belonging to that specific strategy are cleared from the market as quickly and reliably as possible, handling minor network or price fluctuations automatically to ensure the job gets done.
//+-----------------------+
//| Close Everything PAIR |
//|-----------------------+
// used for verbose error logging
#include <stdlib.mqh>
//+-------------+
//| Custom init |
//|-------------+
// Called ONCE when EA is added to chart or recompiled
int init()
{
Comment(" ");
Print("Init complete - script");
}
//+----------------+
//| Custom DE-init |
//+----------------+
// Called ONCE when EA is removed from chart
int deinit()
{
Comment(" ");
Print("DE-Init complete - script");
}
//+-----------+
//| Main |
//+-----------+
// Called EACH TICK and each Bar[]
int start()
{
CloseEverything();
} // start()
//+-----------------+
//| CloseEverything |
//+-----------------+
// Closes all OPEN and PENDING orders
int CloseEverything()
{
int myTyp;
int i;
for( i=(OrdersTotal()-1); i>=0; i-- )
{
OrderSelect(i, SELECT_BY_POS);
if(OrderMagicNumber()==200809241653)
{
switch( OrderType() )
{
//Close opened long positions
case OP_BUY :CloseBuy("TrendHedge close script BUY");
break;
//Close opened short positions
case OP_SELL :CloseSell("TrendHedge close script SELL");
break;
}
}//if
} //for
} // closeeverything
void CloseBuy (string myInfo)
{
int gle;
int cnt;
int loopcount=0;
while(true)
{
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),2,White);
gle=GetLastError();
if(gle==0)
{
Print("CLOSE BUY "+myInfo+" Ticket="+OrderTicket()+" SL="+OrderStopLoss()+" TP="+OrderTakeProfit() );
break;
}
else
{
Sleep(500);
RefreshRates();
Print("-----ERROR----- CLOSE BUY PROFIT Bid="+MarketInfo(OrderSymbol(),MODE_BID)+" error="+gle+" "+ErrorDescription(gle));
}
loopcount++;
if(loopcount>25)
{
Alert("Order failed to CLOSE - See Journal for errors");
break;
}
}//while
}
void CloseSell (string myInfo)
{
int gle;
int cnt;
int loopcount=0;
while(true)
{
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),2,Red);
gle=GetLastError();
if(gle==0)
{
Print("CLOSE SELL "+myInfo+" Ticket="+OrderTicket()+" SL="+OrderStopLoss()+" TP="+OrderTakeProfit() );
break;
}
else
{
Sleep(500);
RefreshRates();
Print("-----ERROR----- CLOSE SELL PROFIT Ask="+MarketInfo(OrderSymbol(),MODE_ASK)+" error="+gle+" "+ErrorDescription(gle));
}
loopcount++;
if(loopcount>25)
{
Alert("Order failed to CLOSE - See Journal for errors");
break;
}
}//while
}
Comments