This tutorial is how to close all trades at once (this only works on MT5).
1st click on custom, then click on create custom blocks to create a custom block.
This code is for the first section. This section is classed as on tick because the block is to be used in the on tick tab, it ends with a ~next~ to activate the next connected block:
startTime = GetMicrosecondCount(); // Record start time
sTrade.SetAsyncMode(true); // Enable asynchronous trade operations
CloseAllPositions(); // Call function to close all positions
PrintPerformance(startTime); // Monitor performance
~next~
This code is for the Global variables, includes section:
#include <Trade/Trade.mqh>
ulong startTime; // To store the start time for performance measurement
CTrade sTrade; // Trade object used for operations
This code is for the custom functions section, when added the function will be named from the first line:
void CloseAllPositions() {
for (int cnt = PositionsTotal() - 1; cnt >= 0 && !IsStopped(); cnt--) {
if (PositionGetTicket(cnt)) {
sTrade.PositionClose(PositionGetInteger(POSITION_TICKET), 100);
uint code = sTrade.ResultRetcode();
Print("Close result code: ", IntegerToString(code));
}
}
}
void PrintPerformance(ulong startTime) {
for (int i = 0; i < 100; i++) {
Print("Elapsed time: ", IntegerToString(GetMicrosecondCount() - startTime), " microseconds. Open positions: ", IntegerToString(PositionsTotal()));
if (PositionsTotal() <= 0) { break; }
Sleep(100);
}
}