8 years ago
Share this article Reddit Twitter Facebook Google+

A little trick on message logging in MT4 code

Today I did some simple back testing in MT4 of an indicator I wrote for a client. I found a problem is that the MQL function Print() doesn't work in back testing. Though the MT4 document says that Print() only doesn't work in optimizing, I found it doesn't work in back testing.

The problem

As the document Operation of Programs in the Strategy Tester explained, I don't mind if Alert doesn't work, but Print() is very important for debugging when the debugger doesn't work for back testing. Message logging is the bottom line for debugging. I found some hard bugs in my script so I need debugging!

The simple solution

I recalled more than ten years when I wrote programs using Win32 API. I had a favorite API,

void WINAPI OutputDebugString(
  _In_opt_ LPCTSTR lpOutputString
);

The function outputs debug message text to any Windows debugger. MT4 only intercepts any MQL functions, and it can't intercept Windows function. That's the key.

Using the code

Below code shows how to use the Windows function,

#import "kernel32.dll"
void OutputDebugStringW(string message);
#import

void printLog(string message)
{
    OutputDebugStringW(message);
    Print(message);
}

Now call printLog instead Print, MT4 can't intercept the message any more.

Note OutputDebugStringW is the Unicode form of OutputDebugString, which works with MQL string type.

Reading the debug message

MT4 can't intercept the message sent by printLog, thus there is no any message in MT4 log panel. Then where to see the message?

Use DbgView from Microsoft!

The neat tool will capture all debug message in the system, so we can view the messages there.