Libraries: MultiTester - page 59

klycko #:

Unfortunately your script doesn't work

I checked - it works. But perhaps we have different interpretations of the set-file concept.

I added these lines in case of a different interpretation.

// Load/Save Tester's set-file.
#property script_show_inputs

input bool inLoad = true; // Settings Load/Save - true/false

#include <fxsaber\MultiTester\MTTester.mqh> // https://www.mql5.com/en/code/26132

#define  EA_INPUTS "[TesterInputs]\r\n"

void OnStart()
{
  const string FileName = __FILE__ + ".set";
  
  string Settings;
  ushort Words[];  
      
  if (inLoad) // Load settings.
  {
    Print("Load: " + (string)FileLoad(FileName, Words));
    Settings = EA_INPUTS + ShortArrayToString(Words, 1); // 1 - Unicode
    
    Print(MTTESTER::SetSettings(Settings));
  
  }
  else if (MTTESTER::GetSettings(Settings)) // Save settings.
  {
    Settings = StringSubstr(Settings, StringFind(Settings, EA_INPUTS) + StringLen(EA_INPUTS));
    
    Words[ArrayResize(Words, 1) - 1] = 0xFEFF; // 1 - Unicode
    
    StringToShortArray(Settings, Words, ArraySize(Words));    
    Print("Save: " + (FileSave(FileName, Words) ? (string)ArraySize(Words) : "error"));
  }
}
fxsaber #:

I checked - it works. But perhaps we have different interpretations of the set-file concept.

I added these lines in case of a different interpretation.

Thank you very much for your time and intelligence!

I have already overcome these difficulties with the help of Google AI.

I sent you this working solution in the form of OX.mq5 script.

Thank you!

metatrader version 5.00
build 5800 17-apr-2026

I'm using the files exactly the same as the .zip

Do you have any suggestions as to what it might be?

Files:
fileapi.mqh  10 kb
winuser.mqh  82 kb
Thomaz Diogo Cimim #:
Do you have any suggestions on what this might be?

It's most likely the wrong version of the mqh file. Everything compiles for me and other users.

// Imports the trading history from the Terminal into the Tester.

#include <fxsaber\SingleTesterCache\SingleTesterCache.mqh> // https://www.mql5.com/en/code/27611
#include <fxsaber\MultiTester\MTTester.mqh> // https://www.mql5.com/en/code/26132

input string inFileName = "Test.tst";

void OnStart()
{  
  SINGLETESTERCACHE SingleTesterCache; // Created a test cache object.
  
  // https://www.mql5.com/ru/forum/330333/page7#comment_60578334
  if (SingleTesterCache.Set() &&          // We have included the actual trading history in it.
      SingleTesterCache.Save(inFileName)) // We’ve saved it to a file that can be imported into the Tester.
  {
    const string FullPath = TerminalInfoString(TERMINAL_DATA_PATH) + "\\MQL5\\Files\\" + inFileName;
    
    MessageBox(MTTESTER::OpenCache(FullPath) ? "Done" : "Failed");
  }
}

I can’t understand why, when using the multitester, the tester completes one task from the list and then stops; the next task doesn’t start until I log in again and open the MetaTrader window manually by switching to it.

Can anyone suggest where I should look?

I’ve already set the background priority and configured priority allocation via the Task Manager, but the testing simply won’t run in the background.

It only works if MetaTrader is running on the desktop and its window is on top of all other windows.




//Google saysthis:

The problem lies in how Windows manages interface rendering, whilst the MultiTester itself ( based on WinAPI / PostMessage / click emulation) mimics user actions.

When the MetaTrader window is minimised, covered by other windows, or you disconnect from the RDP (Remote Desktop) session, Windows disables interface redrawing (rendering) and puts the window into a state where the emulation of keystrokes and mouse clicks ceases to work. To start the next run, the Multitester needs to ‘press’ the ‘Start’ button or shift focus to the settings field, but in an inactive window these commands have no effect.

The solution is to create a virtual desktop.

The MTTester library by fxsaber controls the MT5 tester by intercepting window handles (WinAPI), but when the terminal is covered by other windows or the screen is locked, Windows freezes the rendering of the tester’s controls, preventing the script from reading the status of the ‘Start/Stop’ button or sending a click to it.
On a local PC, this problem can be resolved by following a three-step process:
1. Move MT5 to a separate virtual desktop (the main solution)
This is the most reliable way to get round Windows on a local computer if you’re continuing to use other programmes on it.
  • Press Win + Tab and , at the top (or bottom in Windows 11), click ‘Create desktop’.
  • Drag the MetaTrader 5 window onto this second desktop and maximise it to full screen (do not minimise it!).
  • Return to your first desktop (Win + Ctrl + Left Arrow) and carry on with your work as normal.
  • Why this works: For Windows, the window on the second desktop remains ‘active’, maximised and not covered by other windows. The rendering of the tester’s buttons does not freeze, and MTTester runs tasks in sequence without any issues.
2. Power-saving and screen settings
If you step away from your PC and the screen locks (Win + L) or the monitor goes dark, the graphics subsystem goes back to sleep, and MTTester pauses.
  • Disable the display from switching off: ControlPanel -> Power Options -> Change power plan settings -> ‘Turn off display: Never’. (Simply switch off the monitor itself using the physical button on the casing if you are going to bed for the night).
  • Disable the screensaver and lock screen: Make sure that the screensaver setting in the display settings does not require you to enter a password when you log out.
3. Checking the MTTester code base and MT5 settings
Ensure that the library itself can force the window to wake up if necessary:
  • Enable DLLs: In MT5, go to Tools -> Settings -> Expert Advisors and check that ‘Allow DLL imports’ is ticked (the fxsaber library requires access to user32.dll to locate handles and send messages to the tester window).
  • Check that MTTester.mqh is up to date: In older versions of the library, there were issues with determining the state of the ‘Start’ button in newer MT5 builds when the window was not in focus. If you haven’t updated the library from the MQL5 forum for a while, download the latest version of MTTester.mqh from its code base — fixes specifically for background operation have been added there.
  • Do not minimise the tester window within the terminal: The ‘Strategy Tester’tab within MT5 itself must be open, not hidden behind the price charts.

I just can’t understand why it used to work fine for years, but now we have to play via desktop duplicates?

Answer: It looks like there’s a problem with Windows.

а как решить проблему без виртуального рабочего стола? может мешает какое то приложение или настройки в виндовс

Чтобы MTTester работал в фоне на основном рабочем столе без создания второго стола, нужно заставить Windows не считать окно MT5 свернутым или замороженным, а самой библиотеке — принудительно перехватывать фокус перед каждым новым заданием.
Посторонние приложения (кроме агрессивных «ускорителей ПК» и утилит для энергосбережения) обычно не виноваты — это стандартное поведение ядра Windows и самого MT5. Решить проблему на одном рабочем столе можно четырьмя способами:

1. Включить принудительный перехват фокуса в коде MTTester

В библиотеке MTTester есть встроенные механизмы для пробуждения окна, но по умолчанию Windows запрещает фоновым программам «воровать» фокус у активного окна (чтобы не мешать пользователю).
• Снимите запрет в реестре Windows (ForegroundLockTimeout):
        1. Нажмите Win + R, введите regedit и нажмите Enter.
        2. Перейдите по пути: HKEY_CURRENT_USER\Control Panel\Desktop.
        3. Найдите параметр ForegroundLockTimeout и измените его значение на 0.
        4. Перезагрузите ПК.
(Это позволит библиотеке fxsaber через WinAPI принудительно вытаскивать окно MT5 на долю секунды на передний план, нажимать «Старт» и отдавать фокус обратно).
• Проверьте флаг в скрипте: Убедитесь, что при запуске задач через MTTester не отключен авто-фокус (в свежих версиях MTTester.mqh за это отвечает корректная работа функции MTTESTER::SetActive(), которая срабатывает только при разрешенном импорте DLL).

2. Не сворачивать окно MT5, а «прятать» его (главный трюк)

Главная ошибка — нажимать кнопку «Свернуть» (_) в правом верхнем углу окна MT5. При сворачивании Windows физически убирает окно с экрана.
• Что делать вместо этого: Оставьте окно MT5 развернутым (не свернутым в панель задач!), а свои рабочие окна (браузер, проводник и т.д.) просто открывайте поверх него.
• Чтобы MT5 вообще не мешал на экране, можно уменьшить его окно до минимального размера и сдвинуть в самый угол монитора, но никогда не нажимать кнопку сворачивания. Пока окно в состоянии Normal (даже перекрытое другими окнами), DWM продолжает обновлять его интерфейс.

3. Отключить заморозку фоновых вкладок и энергосбережение Windows

В Windows 10/11 есть встроенный механизм Efficiency Mode (Режим эффективности) и Power Throttling (Троттлинг питания), который автоматически усыпляет фоновые процессы для экономии ресурсов.
• Отключите Power Throttling для MT5:
        1. Откройте командную строку (cmd) от имени Администратора.
        2. Выполните команду (указав ваш путь к terminal64.exe):cmd
powercfg /powerthrottling disable /path "C:\Program Files\MetaTrader 5\terminal64.exe"
Используйте код с осторожностью.
• Отключите таймер отключения экрана в настройках электропитания (поставить «Никогда»).

4. Использовать виртуальный монитор (HDMI/DisplayPort заглушка)

Если на видеокарте есть свободный выход, вставляется копеечная аппаратная заглушка (эмулятор монитора), а в параметрах экрана Windows включается режим «Расширить эти экраны». Окно MT5 перетаскивается на этот второй «виртуальный» экран. Для Windows терминал будет на 100% активным и открытым на отдельном физическом мониторе, но на основном экране он вам мешать не будет (по сути, это аппаратный аналог виртуального рабочего стола, который работает даже при выключенном основном мониторе).
Попробуйте сначала не сворачивать окно MT5 в панель задач (просто перекрывать его другими окнами) и обнулить ForegroundLockTimeout — если хотите, можем также проверить настройки вашего управляющего скрипта, чтобы убедиться, что в нем не заблокирован вызов активного окна.
I tried the registry method described in points 1 and 3; it seems that point 1 really helped, and now it works even without the second desktop, provided I don’t minimise the MetaTrader terminal window
Aleksei Skrypnev #:

The only thing I can’t understand is why it used to be fine for so many years

Have I understood the issue correctly: that now (since when?) MTTester is only guaranteed to work when the Terminal window is active?
fxsaber #:
Have I understood the issue correctly – that MTTester now (when?) only works when the Terminal window is active?

Yes, the Terminal window must be active, and the OS must recognise it correctly. This started happening for me around May or the summer; I’m on Windows 10. I couldn’t figure out the cause myself, but the AI chat on Google Search gave me a clue.

What particularly surprised me was that clicking the ‘Minimise’ button on the Terminal window causes it to stop working: moreover, when you reopen the Terminal, the task update runs, and the task list window shows, for example: the last task was running for 9 hours (instead of one minute); the agents have apparently finished their work and are idle, and then a new task starts.