MQL4 Implementation
Because MT4 overwrites the requested price with the fill price in the history tab for market orders, you cannot extract accurate slippage from OrdersHistoryTotal(). It must be logged in real-time at the exact moment of execution.
This MQL4 snippet provides a real-time trade logger that calculates exact point slippage, tags the execution session based on broker server time, and exports it to a CSV for external histogram analysis.
Code: Select all
//+------------------------------------------------------------------+
//| SessionSlippageLog.mq4 |
//+------------------------------------------------------------------+
#property strict
// Adjust these to match your broker's server time GMT offset
input int LondonStartHour = 8;
input int NYStartHour = 13; // NY open / Overlap start
input int NYEndHour = 17; // London Close / Pure NY afternoon starts here
string logFileName = "Slippage_Log.csv";
// Call this function immediately after a successful OrderSend()
// or when detecting a pending order trigger.
void LogTradeExecution(int ticket, double requestedPrice, double filledPrice, int cmd)
{
if(ticket <= 0) return;
int fileHandle = FileOpen(logFileName, FILE_READ|FILE_WRITE|FILE_CSV|FILE_ANSI, ",");
if(fileHandle == INVALID_HANDLE)
{
Print("Failed to open slippage log file. Error: ", GetLastError());
return;
}
// Move to end of file to append new records
FileSeek(fileHandle, 0, SEEK_END);
// Write headers if the file is newly created
if(FileSize(fileHandle) == 0)
{
FileWrite(fileHandle, "Ticket", "Time", "Symbol", "Side", "Session", "Requested", "Filled", "Slippage_Points");
}
string side = (cmd == OP_BUY) ? "Buy" : "Sell";
string session = GetSession(TimeCurrent());
double slippage = 0;
// Calculate slippage in points (positive = bad slippage, negative = positive slippage)
if(cmd == OP_BUY)
slippage = (filledPrice - requestedPrice) / Point;
else if(cmd == OP_SELL)
slippage = (requestedPrice - filledPrice) / Point;
FileWrite(fileHandle,
IntegerToString(ticket),
TimeToString(TimeCurrent(), TIME_DATE|TIME_MINUTES|TIME_SECONDS),
Symbol(),
side,
session,
DoubleToString(requestedPrice, Digits),
DoubleToString(filledPrice, Digits),
DoubleToString(slippage, 1));
FileClose(fileHandle);
}
// Determines the session bucket based on execution time
string GetSession(datetime time)
{
int hour = TimeHour(time);
if(hour >= LondonStartHour && hour < NYStartHour) return "London";
if(hour >= NYStartHour && hour < NYEndHour) return "Overlap";
if(hour >= NYEndHour && hour < 22) return "New York";
return "Asia"; // Catch-all for 22:00 to 08:00 server time
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.