Re: Shutdown drills for yen traders: a case study approach
Posted: Sun Oct 25, 2026 9:05 pm
Here is the looping script:
Code: Select all
//+------------------------------------------------------------------+
//| CloseAll_RetryMaxSpread_JPY.mq5 |
//+------------------------------------------------------------------+
#property strict
#include <Trade\Trade.mqh>
int MaxSpreadPoints = 500;
void OnStart()
{
CTrade trade;
trade.SetDeviationInPoints(100);
// ==========================================
// 1. DELETE PENDING ORDERS (IMMEDIATE WIPE)
// ==========================================
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong ticket = OrderGetTicket(i);
if(ticket > 0)
{
string symbol = OrderGetString(ORDER_SYMBOL);
if(StringFind(symbol, "JPY") >= 0)
{
trade.OrderDelete(ticket);
}
}
}
Print("All JPY pending orders deleted.");
// ==========================================
// 2. LOOP TO CLOSE POSITIONS
// ==========================================
int attempts = 0;
// IsStopped() ensures the loop breaks if you manually remove the script or close MT5
while(!IsStopped())
{
bool pendingJPYPositions = false;
attempts++;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
string symbol = PositionGetSymbol(i);
if(StringFind(symbol, "JPY") >= 0)
{
long currentSpread = SymbolInfoInteger(symbol, SYMBOL_SPREAD);
if(currentSpread > MaxSpreadPoints)
{
// Flag that we still have JPY exposure due to spread
pendingJPYPositions = true;
Print("Attempt ", attempts, ": Spread for ", symbol, " is ", currentSpread, " - Waiting...");
continue;
}
ulong ticket = PositionGetTicket(i);
if(ticket > 0)
{
if(!trade.PositionClose(ticket))
{
// If the close fails (e.g., requote), flag to try again next loop
pendingJPYPositions = true;
Print("Attempt ", attempts, ": Failed to close ", symbol, ". Retrying...");
}
else
{
Print("Attempt ", attempts, ": Successfully closed ", symbol);
}
}
}
}
// If the loop finished and no JPY positions triggered the flag, we are flat.
if(!pendingJPYPositions)
{
Alert("All JPY positions successfully closed and orders deleted.");
break;
}
// Sleep for 250 milliseconds before checking spreads again to prevent CPU overload
Sleep(250);
}
}